answer
stringlengths
17
10.2M
package controllers; import java.util.List; import models.Bed; import models.Booking; import models.Cabin; import models.LargeCabin; import models.RDate; import models.SmallCabin; import models.User; import org.joda.time.DateTime; import org.joda.time.Days; import org.junit.*; import com.fasterxml.jackson.databind.JsonNode; import JSONFormatters.JsonHelper; import flexjson.JSONSerializer; import static org.junit.Assert.*; import play.mvc.Result; import play.test.FakeRequest; import play.test.WithApplication; import static play.test.Helpers.*; public class BookingControllerTest extends WithApplication { SmallCabin sCabin; LargeCabin lCabin; User userOk; User userBad; final static String authToken = "X-AUTH-TOKEN"; @SuppressWarnings("deprecation") @Before public void setUp() { start(fakeApplication(inMemoryDatabase())); sCabin = new SmallCabin("AvailabilityTestSmallCabin"); lCabin = new LargeCabin("AvailabilityTestLargeCabin", 8); userOk = new User("q@t","w", "t"); userBad = new User("bad@guy.com", "w", "t"); sCabin.save(); lCabin.save(); userOk.save(); Booking b1 = Booking.createBooking(userOk.id, RDate.fDt, RDate.fDt.plusDays(3), lCabin.id, lCabin.beds); b1.save(); } @Test public void testSubmitBooking() { //Normal booking, OK FakeRequest fkRequest = new FakeRequest(POST, "/api/bookings/"); fkRequest.withHeader(authToken, userOk.createToken()); JsonNode node = JsonHelper.getOkBooking(); fkRequest.withJsonBody(node); System.out.println("DEBUGGIN: \n"); System.out.println(node); System.out.println(" Result resOk = route(fkRequest); System.out.println(" assertEquals("SHOULD BE OK", OK, status(resOk)); //TODO this says guestList invalid, where does that error come from? //Can't be because JSON isn't read right, because I had to fix dates being wrong, so it can read //the first part, it just doesn't like the guests part? //Only babies booking fkRequest = new FakeRequest(POST, "/api/bookings/"); fkRequest.withHeader(authToken, userOk.createToken()); fkRequest.withJsonBody(JsonHelper.getOnlyMemberBabiesBookingJSON()); Result resBad = route(fkRequest); System.out.println(" assertEquals("SHOULD BE BAD", BAD_REQUEST, status(resBad)); } @Test public void testCancelBooking() { //cancel booking as other user FakeRequest fkRequest = new FakeRequest(DELETE, "/api/bookings/1"); fkRequest.withHeader(authToken, userBad.createToken()); Result resBad = route(fkRequest); assertEquals(BAD_REQUEST, status(resBad)); System.out.println(" //cancel booking as actual owner of booking fkRequest = new FakeRequest(DELETE, "/api/bookings/1"); //Add id here? fkRequest.withHeader(authToken, userOk.createToken()); Result resOk = route(fkRequest); assertEquals(OK, status(resOk)); System.out.println(" } @Test public void testGetOrderSummary() { } @Test /** Note: Doesn't test the actual controller, just copied the entire code and testing within here TODO **/ public void TestGetAvailabilityForTimePeriodSmallCabin() { //make smallCabin with zero bookings /** add different bookings and test **/ DateTime s1 = new DateTime("2015-03-01"); DateTime e1 = new DateTime("2015-03-03"); Booking b1 = Booking.createBooking(userOk.id, s1, e1, sCabin.id, null); b1.save(); b1.status = Booking.CANCELLED; b1.update(); DateTime s2 = new DateTime("2015-04-25"); DateTime e2 = new DateTime("2015-04-30"); Booking b2 = Booking.createBooking(userOk.id, s2, e2, sCabin.id, null); b2.save(); //DateTime s3 = new DateTime("2015-04-15"); //DateTime e3 = new DateTime("2015-04-10"); //Booking b3 = Booking.createBooking(user.id, s3, e3, sCabin.id, null); Booking can't happen test is else where now //b3.save(); DateTime s4 = new DateTime("2015-03-29"); DateTime e4 = new DateTime("2015-04-05"); Booking b4 = Booking.createBooking(userOk.id, s4, e4, sCabin.id, null); b4.save(); int[] expectedResultArray = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1}; String expectedResultString = "bookedDays "+expectedResultArray; /** END adding bookings **/ //parameters that should be gotten from calendar module (query parameters) DateTime startDate = new DateTime("2015-03-01"); DateTime endDate = new DateTime("2015-04-30"); long cabinId = sCabin.id; /**Start of test code, any debugging here should be transferred to BookingController method**/ int[] smallCabinBookedDays = new int[Math.abs(Days.daysBetween(startDate, endDate).getDays())+1]; JSONSerializer serializer = new JSONSerializer(); String actualResult; Cabin cabin = Cabin.find.byId(cabinId); if(cabin instanceof SmallCabin) { List<Booking> bookings = SmallCabin.findAllBookingsForCabinGivenDate(cabinId, startDate, endDate); if(!bookings.isEmpty()) { for(Booking b: bookings) { //for each booking set bookedDays[i] = +1 for range startDate-endDate int[] indices = utilities.DateHelper.getIndex(startDate, new DateTime(b.dateFrom), new DateTime(b.dateTo)); /** indices[0] startIndex in bookedDays, [1] is endIndex **/ if(indices[0] < 0) //if b.dateFrom precedes startDate, skip to startDate indices[0] = 0; for(int i = indices[0]; i<=indices[1]; i++){ smallCabinBookedDays[i] = 1; //TODO test } } actualResult = ("bookedDays "+ serializer.serialize(smallCabinBookedDays)); } else { //Either something is wrong or the entire given daterange shows available for given cabin actualResult = ("bookedDays " + serializer.serialize(smallCabinBookedDays)); } } else { actualResult = (" status " + "KO "); actualResult += ("message " + "date invalid"); System.out.println("Bad request: "+actualResult); } //System.out.println("ACTUAL: "+Arrays.toString(smallCabinBookedDays)); //System.out.println("EXPECTED: "+Arrays.toString(expectedResultArray)); assertArrayEquals(expectedResultArray, smallCabinBookedDays); } /** Note: Doesn't actually test the controllers, just copied the entire code and testing within here **/ @Test public void TestGetAvailabilityForTimePeriodLargeCabin() { //parameters that should be gotten from JSON object DateTime startDate = new DateTime("2015-03-01"); DateTime endDate = new DateTime("2015-03-28"); long cabinId = lCabin.id; int[] largeCabinBookedDays = new int[Math.abs(Days.daysBetween(startDate, endDate).getDays())+1]; String actualResult; /** add different bookings and test **/ DateTime s1 = new DateTime("2015-03-01"); DateTime e1 = new DateTime("2015-03-03"); List<Bed> arrBeds1 = ((LargeCabin) lCabin).book(1, new DateTime(s1), new DateTime(e1)); Booking b1 = Booking.createBooking(userOk.id, s1, e1, lCabin.id, arrBeds1); b1.save(); DateTime s2 = new DateTime("2015-03-09"); DateTime e2 = new DateTime("2015-03-13"); List<Bed> arrBeds2 = ((LargeCabin) lCabin).book(2, new DateTime(s2), new DateTime(e2)); Booking b2 = Booking.createBooking(userOk.id, s2, e2, lCabin.id, arrBeds2); b2.save(); DateTime s3 = new DateTime("2015-03-23"); DateTime e3 = new DateTime("2015-03-28"); List<Bed> arrBeds3 = ((LargeCabin) lCabin).book(3, new DateTime(s3), new DateTime(e3)); Booking b3 = Booking.createBooking(userOk.id, s3, e3, lCabin.id, arrBeds3); b3.save(); int[] expectedResultArray = {1,1,1,0,0,0,0,0,2,2,2,2,2,0,0,0,0,0,0,0,0,0,3,3,3,3,3,3}; /** END adding bookings **/ Cabin cabin = Cabin.find.byId(cabinId); if(cabin instanceof LargeCabin) { for(Bed beds : ((LargeCabin) cabin).beds) { for(Booking b : beds.bookings) { int[] indices = utilities.DateHelper.getIndex(startDate, new DateTime(b.dateFrom), new DateTime(b.dateTo)); if(indices[0] < 0) //if b.dateFrom precedes startDate, skip to startDate indices[0] = 0; for(int i = indices[0]; i<=indices[1]; i++) { largeCabinBookedDays[i] += 1; //blankets daterange with +1 to indicate that 1 extra bed is taken during that period } } } } else { actualResult = (" status " + "KO "); actualResult += ("message " + "date invalid"); System.out.println("Bad request: "+actualResult); } //System.out.println("ACTUAL: "+Arrays.toString(largeCabinBookedDays)); //System.out.println("EXPECTED: "+Arrays.toString(expectedResultArray)); assertArrayEquals(expectedResultArray, largeCabinBookedDays); } }
/* High level API */ package org.xbill.DNS; import java.util.*; import java.io.*; import java.net.*; /** * High level API for mapping queries to DNS Records. Caching is used * when possible to reduce the number of DNS requests, and a Resolver * is used to perform the queries. A search path can be set or determined * by FindServer, which allows lookups of unqualified names. * @see Resolver * @see FindServer * * @author Brian Wellington */ public final class dns { private static Resolver res; private static Hashtable caches; private static Name [] searchPath; private static boolean searchPathSet; private static boolean initialized; /* Otherwise the class could be instantiated */ private dns() {} synchronized private static void clearCaches() { Enumeration e = caches.elements(); while (e.hasMoreElements()) { Cache c = (Cache)e.nextElement(); c.clearCache(); } } synchronized private static void initialize() { if (initialized) return; initialized = true; if (res == null) { try { setResolver(new ExtendedResolver()); } catch (UnknownHostException uhe) { System.err.println("Failed to initialize resolver"); System.exit(-1); } } if (!searchPathSet) searchPath = FindServer.searchPath(); if (caches == null) caches = new Hashtable(); else clearCaches(); } static boolean matchType(short type1, short type2) { return (type1 == Type.ANY || type2 == Type.ANY || type1 == type2); } /** * Converts an InetAddress into the corresponding domain name * (127.0.0.1 -> 1.0.0.127.IN-ADDR.ARPA.) * @return A String containing the domain name. */ public static String inaddrString(InetAddress addr) { byte [] address = addr.getAddress(); StringBuffer sb = new StringBuffer(); for (int i = 3; i >= 0; i sb.append(address[i] & 0xFF); sb.append("."); } sb.append("IN-ADDR.ARPA."); return sb.toString(); } /** * Converts an String containing an IP address in dotted quad form into the * corresponding domain name. * ex. 127.0.0.1 -> 1.0.0.127.IN-ADDR.ARPA. * @return A String containing the domain name. */ public static String inaddrString(String s) { InetAddress address; try { address = InetAddress.getByName(s); } catch (UnknownHostException e) { return null; } return inaddrString(address); } /** * Sets the Resolver to be used by functions in the dns class */ public static synchronized void setResolver(Resolver _res) { initialize(); res = _res; } /** * Obtains the Resolver used by functions in the dns class. This can be used * to set Resolver properties. */ public static synchronized Resolver getResolver() { initialize(); return res; } /** * Specifies the domains which will be appended to unqualified names before * beginning the lookup process. If this is not set, FindServer will be used. * @see FindServer */ public static synchronized void setSearchPath(String [] domains) { if (domains == null || domains.length == 0) searchPath = null; else { searchPath = new Name[domains.length]; for (int i = 0; i < domains.length; i++) searchPath[i] = new Name(domains[i]); } searchPathSet = true; } /** * Obtains the Cache used by functions in the dns class. This can be used * to perform more specific queries and/or remove elements. * * @param dclass The dns class of data in the cache */ public static synchronized Cache getCache(short dclass) { initialize(); Cache c = (Cache) caches.get(new Short(dclass)); if (c == null) { c = new Cache(dclass); caches.put(new Short(dclass), c); } return c; } /** * Obtains the (class IN) Cache used by functions in the dns class. This * can be used to perform more specific queries and/or remove elements. * * @param dclass The dns class of data in the cache */ public static synchronized Cache getCache() { return getCache(DClass.IN); } private static Record [] lookup(Name name, short type, short dclass, byte cred, int iterations, boolean querysent) { Cache cache; if (iterations > 6) return null; if (Options.check("verbose")) System.err.println("lookup " + name + " " + Type.string(type)); cache = getCache(dclass); SetResponse cached = cache.lookupRecords(name, type, cred); if (Options.check("verbose")) System.err.println(cached); if (cached.isSuccessful()) { RRset [] rrsets = cached.answers(); Vector v = new Vector(); Enumeration e; Record [] answers; int i = 0; for (i = 0; i < rrsets.length; i++) { e = rrsets[i].rrs(); while (e.hasMoreElements()) { v.addElement(e.nextElement()); } } answers = new Record[v.size()]; e = v.elements(); i = 0; while (e.hasMoreElements()) answers[i++] = (Record)e.nextElement(); return answers; } else if (cached.isNXDOMAIN() || cached.isNXRRSET()) { return null; } else if (cached.isCNAME()) { CNAMERecord cname = cached.getCNAME(); return lookup(cname.getTarget(), type, dclass, cred, ++iterations, false); } else if (cached.isDNAME()) { DNAMERecord dname = cached.getDNAME(); return lookup(name.fromDNAME(dname), type, dclass, cred, ++iterations, false); } else if (querysent) { return null; } else { Record question = Record.newRecord(name, type, dclass); Message query = Message.newQuery(question); Message response; try { response = res.send(query); } catch (Exception ex) { return null; } short rcode = response.getHeader().getRcode(); if (rcode == Rcode.NOERROR || rcode == Rcode.NXDOMAIN) cache.addMessage(response); if (rcode != Rcode.NOERROR) return null; return lookup(name, type, dclass, cred, iterations, true); } } /** * Finds records with the given name, type, and class with a certain credibility * @param namestr The name of the desired records * @param type The type of the desired records * @param dclass The class of the desired records * @param cred The minimum credibility of the desired records * @see Credibility * @return The matching records, or null if none are found */ public static Record [] getRecords(String namestr, short type, short dclass, byte cred) { Record [] answers = null; Name name = new Name(namestr); if (!Type.isRR(type) && type != Type.ANY) return null; initialize(); if (searchPath == null || name.isQualified()) answers = lookup(name, type, dclass, cred, 0, false); else { for (int i = 0; i < searchPath.length; i++) { answers = lookup(new Name(namestr, searchPath[i]), type, dclass, cred, 0, false); if (answers != null) break; } } return answers; } /** * Finds credible records with the given name, type, and class * @param namestr The name of the desired records * @param type The type of the desired records * @param dclass The class of the desired records * @return The matching records, or null if none are found */ public static Record [] getRecords(String namestr, short type, short dclass) { return getRecords(namestr, type, dclass, Credibility.NONAUTH_ANSWER); } /** * Finds any records with the given name, type, and class * @param namestr The name of the desired records * @param type The type of the desired records * @param dclass The class of the desired records * @return The matching records, or null if none are found */ public static Record [] getAnyRecords(String namestr, short type, short dclass) { return getRecords(namestr, type, dclass, Credibility.AUTH_ADDITIONAL); } /** * Finds credible records with the given name and type in class IN * @param namestr The name of the desired records * @param type The type of the desired records * @return The matching records, or null if none are found */ public static Record [] getRecords(String name, short type) { return getRecords(name, type, DClass.IN, Credibility.NONAUTH_ANSWER); } /** * Finds any records with the given name and type in class IN * @param namestr The name of the desired records * @param type The type of the desired records * @return The matching records, or null if none are found */ public static Record [] getAnyRecords(String name, short type) { return getRecords(name, type, DClass.IN, Credibility.AUTH_ADDITIONAL); } /** * Finds credible records for the given dotted quad address and type in class IN * @param addr The dotted quad address of the desired records * @param type The type of the desired records * @return The matching records, or null if none are found */ public static Record [] getRecordsByAddress(String addr, short type) { String name = inaddrString(addr); return getRecords(name, type, DClass.IN, Credibility.NONAUTH_ANSWER); } /** * Finds any records for the given dotted quad address and type in class IN * @param addr The dotted quad address of the desired records * @param type The type of the desired records * @return The matching records, or null if none are found */ public static Record [] getAnyRecordsByAddress(String addr, short type) { String name = inaddrString(addr); return getRecords(name, type, DClass.IN, Credibility.AUTH_ADDITIONAL); } }
package org.basex.test.examples; import java.io.IOException; import org.basex.core.*; import org.basex.core.Commands.CmdIndex; import org.basex.core.proc.*; import org.basex.data.XMLSerializer; import org.basex.io.PrintOutput; import org.basex.query.QueryException; import org.basex.query.QueryProcessor; import org.basex.query.item.Item; import org.basex.query.iter.Iter; @SuppressWarnings("unused") public final class DBExample { /** The current database Context. */ static final Context CONTEXT = new Context(); /** Private constructor. */ private DBExample() { } /** * Main method of the example class. * @param args (ignored) command-line arguments * @throws Exception * E */ public static void main(final String[] args) throws Exception { // Creates a new database context, referencing the database. System.out.println("\n=== Create a database from a file."); // Creates a database from the specified file. new CreateDB("input.xml", "Example1").exec(CONTEXT, System.out); // Do some database stuff MaintenanceExamples.run(); // Runs some example Queries QueryExample.run(); } /** * Some Examples in XQuery Evaluation. * This class contains several variants of XQuery Processing in BaseX. * For further information on BaseX Client-Side abilities in * XQuery Processing please see: * @see XQueryExample#main(String[]) */ static final class QueryExample { /** XMLSerializer that generates valid XML Output. */ static XMLSerializer xmlSer; /** * PrintOutput Context. Point the PrintOutput to whatever file * you like to store the serializing results in a file. * You may as well point it to System.out. */ static PrintOutput out = new PrintOutput(System.out); /** * Runs the Example Queries and sets up the XMLSerializer. * @throws Exception * Blabla */ public static void run() throws Exception { // point the serializer to System.out xmlSer = new XMLSerializer(out); // II Evaluate XQueries for the given context System.out.println("\n=== II Evaluating queries."); // Evaluate XQuery and output the result to System.out System.out.println("===== XQuery Proc: direct output."); directOutputExample(); System.out.println("\n===== XQuery Node Iteration and XML Serializing."); iterateExample(); xmlSer.close(); out.close(); } /** * This method exexcutes an XQuery Process for the given database context. * The results are automatically serialized and * printed to an arbitrary OutputStream. * @throws BaseXException * in case your *TODO* */ private static void directOutputExample() throws BaseXException { new XQuery("for $x in .//body//li return $x").exec(CONTEXT, System.out); } /** * Shows how Results can be iterated and serialized one after another * using the {@link QueryProcessor} class. * This is especially useful if you happen to have very big results, * as you will not have to process all resulting nodes at once. * Please note the use of {@link XMLSerializer} to generate * valid XML output. * * @throws BaseXException * in case something went wrong. * @throws QueryException * in case your query was wrong. */ private static void iterateExample() throws BaseXException, QueryException { QueryProcessor qp = new QueryProcessor("for $x in .//body//li return $x", CONTEXT); // Returns a query iterator Iter iter = qp.iter(); Item item; try { while(null != (item = iter.next())) { item.serialize(xmlSer); } } catch(IOException e) { e.printStackTrace(); return; }// Closes the serializer // Closes the query processor } /** * Use XQuery update to .... * *TODO* [MSe] */ private static void updateExample() { // *TODO* } /** Private constructor to avoid class creation.*/ private QueryExample() { } } static final class CollectionExamples { /** Private constructor to avoid class creation. */ private CollectionExamples() { } } /** * @author BaseX Team * This class shows you how to work with XQuery Update */ static final class UpdateExamples { } /** * Examples on Database maintenance. * @author BaseXTeam * Topics covered: <br /> * Index creation & maintenance: * {@link MaintenanceExamples#createIndexes} * <br /> <br /> * Index creation & maintenance: * {@link MaintenanceExamples#createIndexes} */ static final class MaintenanceExamples { /** * PrintOutput Context. Point the PrintOutput to whatever file * you like to store the serializing results in a file. * You may as well point it to System.out. */ static PrintOutput out = new PrintOutput(System.out); /** * Runs the exmaples. * @throws Exception * on error. */ static void run() throws Exception { createDatabase(); createIndexes(); optimizeDB(); // close the PrintOutput. out.close(); } /** * This method creates a new Database. * It then closes the databases and reopens it. * @throws BaseXException * in case the database could not be opened. */ private static void createDatabase() throws BaseXException { // // You may also create Databases from a collection of files. System.out.println("=== Create Database."); // Creates a database new CreateDB("input.xml", "Example1").execute(CONTEXT, out); // Closes the database. System.out.println("=== Close Database."); new Close().execute(CONTEXT, out); System.out.println("=== Reopen Database."); new Open("Example1").execute(CONTEXT); } /** * Method that shows how to invoke the optimization of the index structure. * @throws BaseXException * In case of failing. */ private static void optimizeDB() throws BaseXException { new Optimize().exec(CONTEXT, System.out); } /** * This method shows operations to create and drop indexes. * @throws BaseXException * on error. */ private static void createIndexes() throws BaseXException { // I Index Creation & Maintenance new CreateIndex("fulltext").exec(CONTEXT, System.out); } /** * Information on the currently open database. * @throws BaseXException * whenever it fails. */ private static void info() throws BaseXException { System.out.println("\n=== III information on the specified " + "database context."); // Dumps information on the specified database context new InfoDB().exec(CONTEXT, System.out); } /** * This method shows how to create, drop and modify databases in BaseX. * @throws BaseXException * when it fails. */ private static void creationAndDropping() throws BaseXException { // Closes the database. new Close().exec(CONTEXT, System.out); // new DropDB("Example1").exec(context, System.out); // // XML string. // String xml = "<xml>This is a test</xml>"; // // Creates a database for the specified input. // new CreateDB(xml, "Example2").exec(context, System.out); // // Closes the database. // new Close().exec(context, System.out); // // Opens an existing database // new Open("Example1").exec(context, System.out); // // Dumps information on the specified database context // new InfoDB().exec(context, System.out); // // Closes the database. // new Close().exec(context, System.out); } /** Private constructor. */ private MaintenanceExamples() { } } }
package org.smof.parsers; import org.bson.*; import org.junit.Test; import org.junit.Before; import org.smof.dataModel.TypeGuitar; import java.math.BigDecimal; import static org.junit.Assert.*; @SuppressWarnings("javadoc") public class StringParserTest { private enum DummyEnum { VALUE1, VALUE2 } private StringParser parser; @Before public void setUp() { parser = new StringParser(null, null); } @Test public void serializeToBson_ShouldSerialize_ObjectStringValueCorrectly() { final String testString = "some string"; BsonValue bsonValue = parser.serializeToBson(testString, null); assertEquals(new BsonString(testString), bsonValue); } @Test public void serializeToBson_ShouldSerialize_ObjectEnumValueCorrectly() { AbstractBsonParser abstractBsonParser = new StringParser(null, null); BsonValue bsonValue = abstractBsonParser.serializeToBson(TypeGuitar.ACOUSTIC, null); assertEquals("BsonString{value='ACOUSTIC'}", bsonValue.toString()); } @Test public void serializeToBson_ShouldSerialize_ObjectIntegerValueCorrectly() { AbstractBsonParser abstractBsonParser = new StringParser(null, null); BsonValue bsonValue = abstractBsonParser.serializeToBson(1, null); assertEquals("BsonString{value='1'}", bsonValue.toString()); } @Test(expected = IllegalArgumentException.class) public void serializeToBson_ShouldSerialize_ToNullAnd_RaiseException() { AbstractBsonParser abstractBsonParser = new StringParser(null, null); abstractBsonParser.serializeToBson(BigDecimal.ONE, null); } @Test public void fromBson_ShouldReturn_StringRawValue() { AbstractBsonParser abstractBsonParser = new StringParser(null, null); BsonString bsonString = new BsonString("bsonString"); String string = abstractBsonParser.fromBson(bsonString, String.class, null); assertEquals("bsonString", string); } @Test public void fromBson_ShouldReturn_IntegerRawValue() { AbstractBsonParser abstractBsonParser = new StringParser(null, null); BsonString bsonString = new BsonString("1"); Integer integer = abstractBsonParser.fromBson(bsonString, Integer.class, null); assertEquals(1, integer.intValue()); } @Test public void fromBson_ShouldReturn_EnumRawValue() { final DummyEnum expected = DummyEnum.VALUE1; final BsonString bsonValue = new BsonString(expected.name()); final DummyEnum actual = parser.fromBson(bsonValue, DummyEnum.class, null); assertEquals(expected, actual); } @Test(expected = RuntimeException.class) public void fromBson_ShouldRaise_RuntimeException_IfValueIsNull() { AbstractBsonParser abstractBsonParser = new StringParser(null, null); abstractBsonParser.fromBson(null, Boolean.class, null); } @Test public void isValidBson_ShouldReturn_True() { AbstractBsonParser abstractBsonParser = new StringParser(null, null); boolean validBson = abstractBsonParser.isValidBson(new BsonString("a string")); assertTrue(validBson); } @Test public void isValidBson_ShouldReturn_False() { AbstractBsonParser abstractBsonParser = new StringParser(null, null); boolean validBson = abstractBsonParser.isValidBson(new BsonArray()); assertFalse(validBson); } }
/* * $Id: HashSpeedTest.java,v 1.33 2010-02-04 06:53:56 tlipkis Exp $ */ package org.lockss.test; import java.io.File; import java.security.MessageDigest; import org.lockss.daemon.*; import org.lockss.util.*; import org.lockss.plugin.*; import org.lockss.plugin.simulated.*; import org.lockss.repository.LockssRepositoryImpl; import org.lockss.poller.PollManager; import org.lockss.crawler.NewContentCrawler; import org.lockss.protocol.*; import java.util.Properties; public class HashSpeedTest extends LockssTestCase { private SimulatedArchivalUnit sau; private MockLockssDaemon theDaemon; private static final int DEFAULT_DURATION = 1000; private static final int DEFAULT_BYTESTEP = 1024; private static final int DEFAULT_FILESIZE = 3000; private static int duration = DEFAULT_DURATION; private static int byteStep = DEFAULT_BYTESTEP; private static int fileSize = DEFAULT_FILESIZE; public static void main(String[] args) throws Exception { HashSpeedTest test = new HashSpeedTest(); if (args.length>0) { try { duration = Integer.parseInt(args[0]); if (args.length>1) { byteStep = Integer.parseInt(args[1]); if (args.length>2) { fileSize = Integer.parseInt(args[2]); } } } catch (NumberFormatException ex) { } } test.setUp(duration, byteStep); test.testRunSelf(); test.tearDown(); } public void setUp() throws Exception { super.setUp(); theDaemon = getMockLockssDaemon(); this.setUp(DEFAULT_DURATION, DEFAULT_BYTESTEP); } public void setUp(int duration, int byteStep) throws Exception { String tempDirPath = getTempDir().getAbsolutePath() + File.separator; String auId = "org|lockss|plugin|simulated|SimulatedPlugin.root~" + PropKeyEncoder.encode(tempDirPath); Properties props = new Properties(); props.setProperty(SystemMetrics.PARAM_HASH_TEST_DURATION, ""+duration); props.setProperty(SystemMetrics.PARAM_HASH_TEST_BYTE_STEP, ""+byteStep); props.setProperty(LockssRepositoryImpl.PARAM_CACHE_LOCATION, tempDirPath); props.setProperty("org.lockss.au." + auId + "." + SimulatedPlugin.AU_PARAM_ROOT, tempDirPath); props.setProperty("org.lockss.au." + auId + "." + SimulatedPlugin.AU_PARAM_DEPTH, "3"); props.setProperty("org.lockss.au." + auId + "." + SimulatedPlugin.AU_PARAM_BRANCH, "5"); props.setProperty("org.lockss.au." + auId + "." + SimulatedPlugin.AU_PARAM_NUM_FILES, "5"); props.setProperty("org.lockss.au." + auId + "." + SimulatedPlugin.AU_PARAM_FILE_TYPES, ""+SimulatedContentGenerator.FILE_TYPE_BIN); props.setProperty("org.lockss.au." + auId + "." + SimulatedPlugin.AU_PARAM_BIN_FILE_SIZE, ""+fileSize); ConfigurationUtil.setCurrentConfigFromProps(props); theDaemon.getPluginManager(); theDaemon.getSystemMetrics(); theDaemon.getHashService(); theDaemon.setDaemonInited(true); theDaemon.getPluginManager().startService(); theDaemon.getSystemMetrics().startService(); theDaemon.getHashService().startService(); theDaemon.getPluginManager().startLoadablePlugins(); sau = (SimulatedArchivalUnit)theDaemon.getPluginManager().getAllAus().get(0); theDaemon.getLockssRepository(sau).startService(); theDaemon.setNodeManager(new MockNodeManager(), sau); } public void tearDown() throws Exception { theDaemon.stopDaemon(); super.tearDown(); } public void testRunSelf() throws Exception { createContent(); crawlContent(); hashContent(); } private void createContent() { System.out.println("Generating tree of size 3x5x5 with "+fileSize +"byte files..."); sau.generateContentTree(); } private void crawlContent() { System.out.println("Crawling tree..."); CrawlSpec spec = new SpiderCrawlSpec(sau.getNewContentCrawlUrls(), null); Crawler crawler = new NewContentCrawler(sau, spec, new MockAuState()); crawler.doCrawl(); } private void hashContent() throws Exception { MessageDigest digest = V1LcapMessage.getDefaultMessageDigest(); System.out.println("Hashing-"); System.out.println(" Algorithm: "+digest.getAlgorithm()); System.out.println(" Duration: "+duration+"ms"); System.out.println(" Byte/step: "+byteStep+"bytes"); CachedUrlSetHasher hasher = sau.getAuCachedUrlSet().getContentHasher(digest); SystemMetrics metrics = theDaemon.getSystemMetrics(); double estimate = metrics.measureHashSpeed(hasher, digest); System.out.println("Estimate-"); System.out.println(" Bytes/ms: "+estimate); System.out.println(" GB/hr: "+ ((estimate*Constants.HOUR)/(1024*1024*1024))); } }
package org.voltdb; import java.io.File; import java.net.URL; import org.voltdb.utils.MiscUtils; /** * Wraps VoltDB in a Thread */ public class ServerThread extends Thread { VoltDB.Configuration m_config; boolean initialized = false; public ServerThread(VoltDB.Configuration config) { m_config = config; m_config.m_pathToLicense = getTestLicensePath(); if (m_config.m_leader == null) { m_config.m_leader = ""; } if (!m_config.validate()) { m_config.usage(); System.exit(-1); } // Disable loading the EE if running against HSQL. m_config.m_noLoadLibVOLTDB = m_config.m_backend == BackendTarget.HSQLDB_BACKEND; setName("ServerThread"); } public ServerThread(String pathToCatalog, BackendTarget target) { m_config = new VoltDB.Configuration(); m_config.m_pathToCatalog = pathToCatalog; m_config.m_backend = target; m_config.m_pathToLicense = getTestLicensePath(); m_config.m_leader = ""; // Disable loading the EE if running against HSQL. m_config.m_noLoadLibVOLTDB = m_config.m_backend == BackendTarget.HSQLDB_BACKEND; setName("ServerThread"); } public ServerThread(String pathToCatalog, String pathToDeployment, BackendTarget target) { m_config = new VoltDB.Configuration(); m_config.m_pathToCatalog = pathToCatalog; m_config.m_pathToDeployment = pathToDeployment; m_config.m_backend = target; m_config.m_pathToLicense = getTestLicensePath(); m_config.m_leader = ""; // Disable loading the EE if running against HSQL. m_config.m_noLoadLibVOLTDB = m_config.m_backend == BackendTarget.HSQLDB_BACKEND; if (!m_config.validate()) { m_config.usage(); System.exit(-1); } setName("ServerThread"); } public ServerThread(String pathToCatalog, String pathToDeployment, int internalPort, int zkPort, BackendTarget target) { this(pathToCatalog, pathToDeployment, VoltDB.DEFAULT_INTERNAL_PORT, internalPort, zkPort, target); } public ServerThread(String pathToCatalog, String pathToDeployment, int leaderPort, int internalPort, int zkPort, BackendTarget target) { m_config = new VoltDB.Configuration(); m_config.m_pathToCatalog = pathToCatalog; m_config.m_pathToDeployment = pathToDeployment; m_config.m_backend = target; m_config.m_pathToLicense = getTestLicensePath(); m_config.m_leader = MiscUtils.getHostnameColonPortString("localhost", leaderPort); m_config.m_internalPort = internalPort; m_config.m_zkInterface = "127.0.0.1:" + zkPort; // Disable loading the EE if running against HSQL. m_config.m_noLoadLibVOLTDB = m_config.m_backend == BackendTarget.HSQLDB_BACKEND; if (!m_config.validate()) { m_config.usage(); System.exit(-1); } setName("ServerThread"); } @Override public void run() { VoltDB.initialize(m_config); VoltDB.instance().run(); } public void waitForInitialization() { // Wait until the server has actually started running. while (!VoltDB.instance().isRunning() || VoltDB.instance().getMode() == OperationMode.INITIALIZING) { Thread.yield(); } } public void waitForRejoin() { while (!VoltDB.instance().isRunning() || VoltDB.instance().getMode() == OperationMode.INITIALIZING || VoltDB.instance().rejoining()) { Thread.yield(); } } public void shutdown() throws InterruptedException { assert Thread.currentThread() != this; VoltDB.instance().shutdown(this); this.join(); } public static String getTestLicensePath() { URL resource = ServerThread.class.getResource("valid_subscription.xml"); // in the community edition, any non-empty string // should work fine here, as it won't be checked if (resource == null) return "[community]"; // return the filesystem path File licxml = new File(resource.getFile()); return licxml.getPath(); } }
package net.varkhan.data.learn.decision; import junit.framework.TestCase; import net.varkhan.base.functor.Mapper; import net.varkhan.base.functor.curry.Pair; import net.varkhan.base.functor.generator.GaussianNumberGenerator; import net.varkhan.base.functor.generator.UniformPRNGDef; import net.varkhan.data.learn.stats.InformationGain; import java.util.Iterator; import java.util.Random; /** * <b></b>. * <p/> * * @author varkhan * @date 1/25/14 * @time 10:11 PM */ public class DecisionLearnerTest extends TestCase { protected static Mapper<String,Double,Object> bucket=new Mapper<String,Double,Object>() { @Override public String invoke(Double arg, Object ctx) { if(arg==null) return null; double v = arg; if(v<0) return "]...0]"; if(v<1) return "[0..1]"; if(v<2) return "[1..2]"; if(v<3) return "[2..3]"; if(v<4) return "[3..4]"; return "[4...["; } }; protected static Iterable<Pair<Double,String>> sample(final Random rand, final int num, final double err) { return new Iterable<Pair<Double,String>>() { @Override public Iterator<Pair<Double,String>> iterator() { final GaussianNumberGenerator<Object> rng=new GaussianNumberGenerator<Object>(new UniformPRNGDef(rand), 0, err); return new Iterator<Pair<Double,String>>() { protected volatile int cnt=0; @Override public boolean hasNext() { return cnt<num; } @Override public Pair<Double,String> next() { cnt ++; double v = rand.nextDouble()*10-3; double b = v + rng.invoke(null); String s = bucket.invoke(b,null); return new Pair.Value<Double,String>(v, s); } @Override public void remove() { } }; } }; } protected static DiscretePartitionFactory<String,Long,Double,Object> createSplitPartition(final int s) { return new DiscretePartitionFactory<String,Long,Double,Object>( new Mapper<Long,Double,Object>() { @Override public Long invoke(Double arg, Object ctx) { return arg==null ? null : arg>s ? Long.valueOf(+1) : arg<s ? Long.valueOf(-1) : Long.valueOf(0); } @Override public String toString() { return "<"+s+">($)"; } }, 3, new InformationGain<String,Object>() ); } public void testTrain() throws Exception { Random rand=new Random(); testTrain(rand, 100, 100, 0.03, 0.05); testTrain(rand, 100, 100, 0.05, 0.10); testTrain(rand, 100, 100, 0.10, 0.15); testTrain(rand, 100, 100, 0.20, 0.20); testTrain(rand, 100, 100, 0.30, 0.25); testTrain(rand, 100, 100, 0.40, 0.30); testTrain(rand, 30, 300, 0.03, 0.02); testTrain(rand, 30, 300, 0.05, 0.03); testTrain(rand, 30, 300, 0.10, 0.10); testTrain(rand, 30, 300, 0.20, 0.20); testTrain(rand, 30, 300, 0.30, 0.25); testTrain(rand, 30, 300, 0.40, 0.30); testTrain(rand, 10, 1000, 0.10, 0.05); testTrain(rand, 10, 1000, 0.20, 0.15); testTrain(rand, 10, 1000, 0.30, 0.25); testTrain(rand, 10, 1000, 0.40, 0.30); // Not much improvement is to be expected at these noise levels by just increasing the # of samples testTrain(rand, 10, 3000, 0.20, 0.15); testTrain(rand, 10, 3000, 0.30, 0.25); testTrain(rand, 10, 3000, 0.40, 0.30); } public void testTrain(Random rand, int run, int num, double err, double max) throws Exception { double inv = 0; for(int i=0; i<run; i++) { inv += runTrain(rand, num, err); } inv /= run; System.out.printf("Inv for %3d runs of %5d +/-%4f = %5f / %5f\n",run,num,err,inv,max); assertTrue("error rate "+inv+" / "+max,inv<max); } public double runTrain(Random rand, int num, double err) throws Exception { DecisionLearner<String,Double,Object> learner = new DecisionLearner<String,Double,Object>( 0.7, // Min confidence 10, // Max depth createSplitPartition(0), createSplitPartition(1), createSplitPartition(2), createSplitPartition(3), createSplitPartition(4) ); for(Pair<Double,String> obs: sample(rand, num, err)) { learner.train(obs.lvalue(),obs.rvalue(), null); // System.out.println("Tree:\n"+learner.model().toString()); } DecisionTree<String,Double,Object> model=learner.model(); // System.out.println("Tree for "+num+" +/-"+err+":\n"+model.toString()); int tst = 0; int inv = 0; for(double v=-3;v<7;v+=0.1) { if(!bucket.invoke(v,null).equals(model.invoke(v,null))) inv++; // System.out.printf("%4f:\t%s\t%s\n",v,bucket.invoke(v,null),model.invoke(v,null)); tst ++; } return (double)inv/(double)tst; } // public void testTrainPartial() throws Exception { }
import behaviorism.utils.Utils; import java.awt.Point; import java.awt.event.KeyEvent; import java.io.File; import java.util.*; public class LineMaker { static boolean OUTPUT_JSON = true; static int MAX_LINES = 50; //max collocated lines per iteration static int NUM_LINES = 30; //num iterations public Word lastSelected = null; public static void main(String[] args) { int NUM_LINES = 2000000; //1. LOAD STUFF IN AND DO INITIAL ANALYSIS Parser.loadInPoems(new File("EmilyDickinsonPoems.txt"), NUM_LINES); Parser.rankWords(); //Parser.rankLines(); //Parser.printPoems(); //Parser.printWordRank(1, 10); //Parser.printLineRank(3900, 5000); // PoetryChain pc = Parser.connectWords("eye", "eyes", 8,8); // pc.printChain(); //Parser.printPoems(); //Parser.printCollocation("my"); System.err.println("TOTAL NUMBER WORDS = " + Parser.rankedWords.size()); //makeChains(); //or, B //Word word = Utils.randomElement(Parser.rankedWords, 10000, 18000); //get a low frequency word //makeNets(word, 10); makeLines(); } public static <T> List<T> randomElements(Collection<T> collection, int howMany) { if (collection.size() < howMany) { System.err.println("ERROR : you are requesting too many elements from this list!"); return null; } List<T> list = new ArrayList<T>(collection); Collections.shuffle(list); List<T> returnList = new ArrayList<T>(); for (int i = 0; i < howMany; i++) { returnList.add(list.get(i)); } return returnList; } private static void makeLines() { Set<Line> uniquelist; List<Line> lines; Word word; Line line; lines = Parser.lines; if (OUTPUT_JSON) { System.out.print("[\n"); } for (int i = 0; i < NUM_LINES; i++) { //1. grab a line at random line = LineMaker.randomElements(lines, 1).get(0); if (OUTPUT_JSON) { System.out.print("\t{\n\t\t\"line\":\"" + line.text + "\",\n"); } else { System.out.println("line = " + line.text); } for (;;) { //2. pick a word in that line at random word = LineMaker.randomElements(line.words, 1).get(0); //3. grab every other line that contains that word uniquelist = new HashSet<Line>(word.lines); //a word appear more than once in a line! if (uniquelist.size() > 1) { //make sure that this is not the only time the word appears in the entire corpus! if (OUTPUT_JSON) { System.out.print("\t\t\"word\":\"" + word + "\",\n"); } else { System.out.println("word = " + word); } break; } } lines = new ArrayList<Line>(uniquelist); lines = lines.subList(0, Math.min(lines.size(), MAX_LINES - 1)); if (OUTPUT_JSON) { System.out.print("\t\t\"lines\":[\n"); } for (int j = 0; j < lines.size(); j++) { Line l = lines.get(j); if (OUTPUT_JSON) { System.out.print("\t\t\t\"" + l.text + "\""); if (j < lines.size() - 1) { System.out.print(",\n"); } else { System.out.print("\n"); } } else { System.out.println(l.stanza.stanzaNum + ":" + l.lineNumber + ": " + l.text); } } if (OUTPUT_JSON) { if (i < NUM_LINES - 1) { System.out.print("\t\t]\n\t},\n"); } else { System.out.print("\t\t]\n\t}\n]\n"); } } } } }
package org.jboss.as.test.clustering.cluster.ejb3.xpc; import static org.jboss.as.test.clustering.ClusteringTestConstants.CONTAINER_1; import static org.jboss.as.test.clustering.ClusteringTestConstants.CONTAINER_2; import static org.jboss.as.test.clustering.ClusteringTestConstants.DEPLOYMENT_1; import static org.jboss.as.test.clustering.ClusteringTestConstants.DEPLOYMENT_2; import static org.jboss.as.test.clustering.ClusteringTestConstants.GRACE_TIME; import static org.jboss.as.test.clustering.ClusteringTestConstants.GRACE_TIME_TO_MEMBERSHIP_CHANGE; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.URL; import java.util.Date; import java.util.Properties; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.jboss.arquillian.container.test.api.ContainerController; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.junit.InSequence; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.clustering.EJBDirectory; import org.jboss.as.test.clustering.cluster.ejb3.xpc.bean.StatefulBean; import org.jboss.as.test.http.util.HttpClientUtils; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * @author Paul Ferraro * @author Scott Marlow * */ @RunWith(Arquillian.class) @RunAsClient public class StatefulWithXPCFailoverTestCase { private static final String persistence_xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> " + "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">" + " <persistence-unit name=\"mypc\">" + " <description>Persistence Unit." + " </description>" + " <jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>" + "<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>" + "<properties> <property name=\"hibernate.hbm2ddl.auto\" value=\"create-drop\"/>" + "<property name=\"hibernate.cache.use_second_level_cache\" value=\"true\" />" + "<property name=\"hibernate.generate_statistics\" value=\"true\" />" + "<property name=\"hibernate.show_sql\" value=\"true\"/>" + "</properties>" + " </persistence-unit>" + "</persistence>"; @ArquillianResource ContainerController controller; @ArquillianResource Deployer deployer; @BeforeClass public static void printSysProps() { Properties sysprops = System.getProperties(); System.out.println("System properties:\n" + sysprops); } @Deployment(name = DEPLOYMENT_1, managed = false, testable = false) @TargetsContainer(CONTAINER_1) public static Archive<?> deployment0() { return createDeployment(); } @Deployment(name = DEPLOYMENT_2, managed = false, testable = false) @TargetsContainer(CONTAINER_2) public static Archive<?> deployment1() { return createDeployment(); } private static Archive<?> createDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, "stateful.war"); war.addPackage(StatefulBean.class.getPackage()); war.addPackage(EJBDirectory.class.getPackage()); war.setWebXML(StatefulBean.class.getPackage(), "web.xml"); war.addAsResource(new StringAsset(persistence_xml), "META-INF/persistence.xml"); System.out.println(war.toString(true)); return war; } @Test @InSequence(1) public void testArquillianWorkaroundSecond() { // Container is unmanaged, need to start manually. start(DEPLOYMENT_1, CONTAINER_1); // TODO: This is nasty. I need to start it to be able to inject it later and then stop it again! start(DEPLOYMENT_2, CONTAINER_2); } @Test @InSequence(2) public void testBasicXPC( @ArquillianResource() @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource() @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws IOException, InterruptedException { // TODO: This is nasty. I need to start it to be able to inject it later and then stop it again! stop(DEPLOYMENT_2, CONTAINER_2); DefaultHttpClient client = HttpClientUtils.relaxedCookieHttpClient(); String xpc1_create_url = baseURL1 + "count?command=createEmployee"; String xpc1_get_url = baseURL1 + "count?command=getEmployee"; String xpc2_get_url = baseURL2 + "count?command=getEmployee"; String xpc1_getempsecond_url = baseURL1 + "count?command=getSecondBeanEmployee"; String xpc2_getempsecond_url = baseURL2 + "count?command=getSecondBeanEmployee"; String xpc2_getdestroy_url = baseURL2 + "count?command=destroy"; try { // extended persistence context is available on node1 System.out.println(new Date() + "create employee entity "); String employeeName = executeUrlWithAnswer(client, xpc1_create_url, "create entity that lives in the extended persistence context that this test will verify is always available"); assertEquals(employeeName, "Tom Brady"); System.out.println(new Date() + "1. about to read entity on node1"); // ensure that we can get it from node 1 employeeName = executeUrlWithAnswer(client, xpc1_get_url, "1. xpc on node1, node1 should be able to read entity on node1"); assertEquals(employeeName, "Tom Brady"); employeeName = executeUrlWithAnswer(client, xpc1_getempsecond_url, "1. xpc on node1, node1 should be able to read entity from second bean on node1"); assertEquals(employeeName, "Tom Brady"); start(DEPLOYMENT_2, CONTAINER_2); System.out.println(new Date() + "2. started node2 + deployed, about to read entity on node1"); employeeName = executeUrlWithAnswer(client, xpc2_get_url, "2. started node2, xpc on node1, node1 should be able to read entity on node1"); assertEquals(employeeName, "Tom Brady"); employeeName = executeUrlWithAnswer(client, xpc2_getempsecond_url, "2. started node2, xpc on node1, node1 should be able to read entity from second bean on node1"); assertEquals(employeeName, "Tom Brady"); // failover to deployment2 stop(DEPLOYMENT_1, CONTAINER_1); // failover #1 to node 2 System.out.println(new Date() + "3. stopped node1 to force failover, about to read entity on node2"); employeeName = executeUrlWithAnswer(client, xpc2_get_url, "3. stopped deployment on node1, xpc should failover to node2, node2 should be able to read entity from xpc"); assertEquals(employeeName, "Tom Brady"); employeeName = executeUrlWithAnswer(client, xpc2_getempsecond_url, "3. stopped deployment on node1, xpc should failover to node2, node2 should be able to read entity from xpc that is on node2 (second bean)"); assertEquals(employeeName, "Tom Brady"); String destroyed = executeUrlWithAnswer(client, xpc2_getdestroy_url, "4. destroy the bean on node2"); assertEquals(destroyed, "destroy"); System.out.println(new Date() + "4. test is done"); } finally { client.getConnectionManager().shutdown(); stop(DEPLOYMENT_1, CONTAINER_1); stop(DEPLOYMENT_2, CONTAINER_2); } } /** * Use the second level cache statistics to ensure that deleting an entity on a cluster node, will * remove the entity from the second level cache on other nodes. * * Note that this test writes to the separate databases on both cluster nodes (so that both nodes can * read the entity from the database). The important thing is that the second level cache entries are * invalidated when the entity is deleted from either database. * * @param baseURL1 * @param baseURL2 * @throws IOException * @throws InterruptedException */ @Test @InSequence(3) public void testSecondLevelCache( @ArquillianResource() @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource() @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws IOException, InterruptedException { start(DEPLOYMENT_1, CONTAINER_1); start(DEPLOYMENT_2, CONTAINER_2); DefaultHttpClient client = new DefaultHttpClient(); String xpc1_create_url = baseURL1 + "count?command=createEmployee"; String xpc2_create_url = baseURL2 + "count?command=createEmployee"; String xpc1_flush_url = baseURL1 + "count?command=flush"; String xpc2_flush_url = baseURL2 + "count?command=flush"; String xpc1_clear_url = baseURL1 + "count?command=clear"; String xpc2_clear_url = baseURL2 + "count?command=clear"; String xpc1_echo_url = baseURL1 + "count?command=echo&message="; String xpc2_echo_url = baseURL2 + "count?command=echo&message="; String xpc1_get_url = baseURL1 + "count?command=getEmployee"; String xpc2_get_url = baseURL2 + "count?command=getEmployee"; String xpc1_getdestroy_url = baseURL2 + "count?command=destroy"; String xpc1_delete_url = baseURL1 + "count?command=deleteEmployee"; String xpc2_delete_url = baseURL2 + "count?command=deleteEmployee"; String xpc1_secondLevelCacheEntries_url = baseURL1 + "count?command=getEmployeesInSecondLevelCache"; String xpc2_secondLevelCacheEntries_url = baseURL2 + "count?command=getEmployeesInSecondLevelCache"; try { assertExecuteUrl(client, xpc1_echo_url + "StartingTestSecondLevelCache"); // echo message to server.log assertExecuteUrl(client,xpc2_echo_url + "StartingTestSecondLevelCache"); // echo message to server.log String employeeName = executeUrlWithAnswer(client, xpc1_create_url, "create entity in node1 in memory db"); assertEquals(employeeName, "Tom Brady"); System.out.println(new Date() + "about to read entity on node1 (from xpc queue)"); employeeName = executeUrlWithAnswer(client, xpc1_get_url, "on node1, node1 should be able to read entity on node1"); assertEquals(employeeName, "Tom Brady"); String employeesInCache = executeUrlWithAnswer(client,xpc1_secondLevelCacheEntries_url, "get number of elements in node1 second level cache (should be zero)"); assertEquals(employeesInCache, "0"); // we read the entity from the extended persistence context (hasn't been flushed yet) assertExecuteUrl(client, xpc1_flush_url); // flush changes to db assertExecuteUrl(client, xpc1_clear_url); // clear xpc state so we have to reload employeeName = executeUrlWithAnswer(client, xpc2_create_url, "create entity in node2 in memory db (each node has its own database)"); assertEquals(employeeName, "Tom Brady"); assertExecuteUrl(client, xpc2_flush_url); // flush changes to db on second node assertExecuteUrl(client, xpc2_clear_url); // clear xpc state so we have to reload employeeName = executeUrlWithAnswer(client, xpc2_get_url, "node2 should be able to read entity from 2lc"); assertEquals(employeeName, "Tom Brady"); // we should of read one Employee entity on node2, ensure the second level cache contains one entry employeesInCache = executeUrlWithAnswer(client,xpc2_secondLevelCacheEntries_url, "get number of elements in node2 second level cache (should be zero)"); assertEquals(employeesInCache, "1"); assertExecuteUrl(client,xpc1_echo_url + "testSecondLevelCacheclearedXPC"); assertExecuteUrl(client,xpc2_echo_url + "testSecondLevelCacheclearedXPC"); assertExecuteUrl(client,xpc2_delete_url); // deleting the entity on one node should remove it from both nodes second level cache assertExecuteUrl(client,xpc1_echo_url + "testSecondLevelCachedeletedEnityOnNode2"); assertExecuteUrl(client,xpc1_echo_url + "2lcOnNode1ShouldHaveZeroElemementsLoaded"); employeesInCache = executeUrlWithAnswer(client,xpc1_secondLevelCacheEntries_url, "get number of elements in node1 second level cache (should be zero)"); assertEquals(employeesInCache, "0"); employeesInCache = executeUrlWithAnswer(client,xpc2_secondLevelCacheEntries_url, "get number of elements in node2 second level cache (should be zero)"); assertEquals(employeesInCache, "0"); assertExecuteUrl(client, xpc1_delete_url); String destroyed = executeUrlWithAnswer(client, xpc1_getdestroy_url, "destroy the bean on node1"); assertEquals(destroyed, "destroy"); } finally { client.getConnectionManager().shutdown(); stop(DEPLOYMENT_1, CONTAINER_1); stop(DEPLOYMENT_2, CONTAINER_2); } } private String executeUrlWithAnswer(DefaultHttpClient client, String url, String message) throws IOException, InterruptedException { int maxWait = GRACE_TIME; while (maxWait > 0) { HttpResponse response = client.execute(new HttpGet(url)); try { if (response.getStatusLine().getStatusCode() < 400 || response.getStatusLine().getStatusCode() > 500) { assertEquals(200, response.getStatusLine().getStatusCode()); Header header = response.getFirstHeader("answer"); if (header != null) { return header.getValue(); } throw new AssertionError("assertExecuteUrlWithResult didn't get expected answer from executed url=" + url + ", " + message); } } finally { response.getEntity().getContent().close(); } maxWait -= 100; Thread.sleep(100); } throw new AssertionError("assertExecuteUrlWithResult Timed out trying to execute url=" + url +", " + message); } private void assertExecuteUrl(DefaultHttpClient client, String url) throws IOException, InterruptedException { int maxWait = GRACE_TIME; while (maxWait > 0) { HttpResponse response = client.execute(new HttpGet(url)); try { if (response.getStatusLine().getStatusCode() < 400 || response.getStatusLine().getStatusCode() > 500) { assertEquals(200, response.getStatusLine().getStatusCode()); return; } } finally { response.getEntity().getContent().close(); } maxWait -= 100; Thread.sleep(100); } throw new AssertionError("assertExecuteUrl Timed out trying to execute url=" + url); } private void stop(String deployment, String container) { try { System.out.println(new Date() + "stopping deployment="+deployment+", container="+container); deployer.undeploy(deployment); controller.stop(container); System.out.println(new Date() + "stopped deployment="+deployment+", container="+container); // On stopping, we issue a request immediately and the request fails due to SuspectedException // TODO: replace with view listener Thread.sleep(GRACE_TIME_TO_MEMBERSHIP_CHANGE); } catch (Throwable e) { e.printStackTrace(System.err); } } private void start(String deployment, String container) { try { System.out.println(new Date() + "starting deployment="+deployment+", container="+ container); controller.start(container); deployer.deploy(deployment); System.out.println(new Date() + "started deployment="+deployment+", container=" + container); } catch (Throwable e) { e.printStackTrace(System.err); } } }
package org.elasticsearch.xpack.ml.integration; import org.apache.http.util.EntityUtils; import org.elasticsearch.client.Request; import org.elasticsearch.client.Response; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.test.SecuritySettingsSourceField; import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken; import java.io.IOException; import java.util.Base64; /** * This test uses a tiny hardcoded base64 encoded PyTorch TorchScript model. * The model was created with the following python script and returns a * Tensor of 1s. The simplicity of the model is not important as the aim * is to test loading a model into the PyTorch process and evaluating it. * * ## Start Python * import torch * class SuperSimple(torch.nn.Module): * def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None): * return torch.ones((input_ids.size()[0], 2), dtype=torch.float32) * * model = SuperSimple() * input_ids = torch.tensor([1, 2, 3, 4, 5]) * the_rest = torch.ones(5) * result = model.forward(input_ids, the_rest, the_rest, the_rest) * print(result) * * traced_model = torch.jit.trace(model, (input_ids, the_rest, the_rest, the_rest)) * torch.jit.save(traced_model, "simplemodel.pt") * ## End Python */ import static org.hamcrest.Matchers.equalTo; public class PyTorchModelIT extends ESRestTestCase { private static final String BASIC_AUTH_VALUE_SUPER_USER = UsernamePasswordToken.basicAuthHeaderValue("x_pack_rest_user", SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING); @Override protected Settings restClientSettings() { return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", BASIC_AUTH_VALUE_SUPER_USER).build(); } private static final String MODEL_INDEX = "model_store"; private static final String MODEL_ID ="simple_model_to_evaluate"; private static final String BASE_64_ENCODED_MODEL = "UEsDBAAACAgAAAAAAAAAAAAAAAAAAAAAAAAUAA4Ac2ltcGxlbW9kZWwvZGF0YS5wa2xGQgoAWlpaWlpaWlpaWoACY19fdG9yY2hfXwp" + "TdXBlclNpbXBsZQpxACmBfShYCAAAAHRyYWluaW5ncQGIdWJxAi5QSwcIXOpBBDQAAAA0AAAAUEsDBBQACAgIAAAAAAAAAAAAAAAAAA" + "AAAAAdAEEAc2ltcGxlbW9kZWwvY29kZS9fX3RvcmNoX18ucHlGQj0AWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaW" + "lpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWnWOMWvDMBCF9/yKI5MMrnHTQsHgjt2aJdlCEIp9SgWSTpykFvfXV1htaYds0nfv473Jqhjh" + "kAPywbhgUbzSnC02wwZAyqBYOUzIUUoY4XRe6SVr/Q8lVsYbf4UBLkS2kBk1aOIPxbOIaPVQtEQ8vUnZ/WlrSxTA+JCTNHMc4Ig+Ele" + "s+Jod+iR3N/jDDf74wxu4e/5+DmtE9mUyhdgFNq7bZ3ekehbruC6aTxS/c1rom6Z698WrEfIYxcn4JGTftLA7tzCnJeD41IJVC+U07k" + "umUHw3E47Vqh+xnULeFisYLx064mV8UTZibWFMmX0p23wBUEsHCE0EGH3yAAAAlwEAAFBLAwQUAAgICAAAAAAAAAAAAAAAAAAAAAAAJ" + "wA5AHNpbXBsZW1vZGVsL2NvZGUvX190b3JjaF9fLnB5LmRlYnVnX3BrbEZCNQBaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpa" + "WlpaWlpaWlpaWlpaWlpaWlpaWlpaWrWST0+DMBiHW6bOod/BGS94kKpo2Mwyox5x3pbgiXSAFtdR/nQu3IwHiZ9oX88CaeGu9tL0efq" + "+v8P7fmiGA1wgTgoIcECZQqe6vmYD6G4hAJOcB1E8NazTm+ELyzY4C3Q0z8MsRwF+j4JlQUPEEo5wjH0WB9hCNFqgpOCExZY5QnnEw7" + "ME+0v8GuaIs8wnKI7RigVrKkBzm0lh2OdjkeHllG28f066vK6SfEypF60S+vuYt4gjj2fYr/uPrSvRv356TepfJ9iWJRN0OaELQSZN3" + "FRPNbcP1PTSntMr0x0HzLZQjPYIEo3UaFeiISRKH0Mil+BE/dyT1m7tCBLwVO1MX4DK3bbuTlXuy8r71j5Aoho66udAoseOnrdVzx28" + "UFW6ROuO/lT6QKKyo79VU54emj9QSwcInsUTEDMBAAAFAwAAUEsDBAAACAgAAAAAAAAAAAAAAAAAAAAAAAAZAAYAc2ltcGxlbW9kZWw" + "vY29uc3RhbnRzLnBrbEZCAgBaWoACKS5QSwcIbS8JVwQAAAAEAAAAUEsDBAAACAgAAAAAAAAAAAAAAAAAAAAAAAATADsAc2ltcGxlbW" + "9kZWwvdmVyc2lvbkZCNwBaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaMwpQSwcI0" + "Z5nVQIAAAACAAAAUEsBAgAAAAAICAAAAAAAAFzqQQQ0AAAANAAAABQAAAAAAAAAAAAAAAAAAAAAAHNpbXBsZW1vZGVsL2RhdGEucGts" + "UEsBAgAAFAAICAgAAAAAAE0EGH3yAAAAlwEAAB0AAAAAAAAAAAAAAAAAhAAAAHNpbXBsZW1vZGVsL2NvZGUvX190b3JjaF9fLnB5UEs" + "BAgAAFAAICAgAAAAAAJ7FExAzAQAABQMAACcAAAAAAAAAAAAAAAAAAgIAAHNpbXBsZW1vZGVsL2NvZGUvX190b3JjaF9fLnB5LmRlYn" + "VnX3BrbFBLAQIAAAAACAgAAAAAAABtLwlXBAAAAAQAAAAZAAAAAAAAAAAAAAAAAMMDAABzaW1wbGVtb2RlbC9jb25zdGFudHMucGtsU" + "EsBAgAAAAAICAAAAAAAANGeZ1UCAAAAAgAAABMAAAAAAAAAAAAAAAAAFAQAAHNpbXBsZW1vZGVsL3ZlcnNpb25QSwYGLAAAAAAAAAAe" + "Ay0AAAAAAAAAAAAFAAAAAAAAAAUAAAAAAAAAagEAAAAAAACSBAAAAAAAAFBLBgcAAAAA/AUAAAAAAAABAAAAUEsFBgAAAAAFAAUAagE" + "AAJIEAAAAAA=="; private static final int RAW_MODEL_SIZE; // size of the model before base64 encoding static { RAW_MODEL_SIZE = Base64.getDecoder().decode(BASE_64_ENCODED_MODEL).length; } @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/73769") public void testEvaluate() throws IOException { createModelStoreIndex(); putTaskConfig(); putModelDefinition(); createTrainedModel(); startDeployment(); try { Response inference = infer("my words"); assertThat(EntityUtils.toString(inference.getEntity()), equalTo("{\"inference\":[[1.0,1.0]]}")); } finally { stopDeployment(); } } private void putModelDefinition() throws IOException { Request request = new Request("PUT", "/" + MODEL_INDEX + "/_doc/trained_model_definition_doc-" + MODEL_ID + "-0"); request.setJsonEntity("{ " + "\"doc_type\": \"trained_model_definition_doc\"," + "\"model_id\": \"" + MODEL_ID +"\"," + "\"doc_num\": 0," + "\"definition_length\":" + RAW_MODEL_SIZE + "," + "\"total_definition_length\":" + RAW_MODEL_SIZE + "," + "\"compression_version\": 1," + "\"definition\": \"" + BASE_64_ENCODED_MODEL + "\"," + "\"eos\": true" + "}"); client().performRequest(request); } private void createModelStoreIndex() throws IOException { Request request = new Request("PUT", "/" + MODEL_INDEX); request.setJsonEntity("{ " + "\"mappings\": {\n" + " \"properties\": {\n" + " \"doc_type\": { \"type\": \"keyword\" },\n" + " \"model_id\": { \"type\": \"keyword\" },\n" + " \"definition_length\": { \"type\": \"long\" },\n" + " \"total_definition_length\": { \"type\": \"long\" },\n" + " \"compression_version\": { \"type\": \"long\" },\n" + " \"definition\": { \"type\": \"binary\" },\n" + " \"eos\": { \"type\": \"boolean\" },\n" + " \"task_type\": { \"type\": \"keyword\" },\n" + " \"vocab\": { \"type\": \"keyword\" },\n" + " \"with_special_tokens\": { \"type\": \"boolean\" },\n" + " \"do_lower_case\": { \"type\": \"boolean\" }\n" + " }\n" + " }" + "}"); client().performRequest(request); } private void putTaskConfig() throws IOException { Request request = new Request("PUT", "/" + MODEL_INDEX + "/_doc/" + MODEL_ID + "_task_config"); request.setJsonEntity("{ " + "\"task_type\": \"bert_pass_through\",\n" + "\"with_special_tokens\": false," + "\"vocab\": [\"these\", \"are\", \"my\", \"words\"]\n" + "}"); client().performRequest(request); } private void createTrainedModel() throws IOException { Request request = new Request("PUT", "/_ml/trained_models/" + MODEL_ID); request.setJsonEntity("{ " + " \"description\": \"simple model for testing\",\n" + " \"model_type\": \"pytorch\",\n" + " \"inference_config\": {\n" + " \"classification\": {\n" + " \"num_top_classes\": 1\n" + " }\n" + " },\n" + " \"input\": {\n" + " \"field_names\": [\"text_field\"]\n" + " },\n" + " \"location\": {\n" + " \"index\": {\n" + " \"model_id\": \"" + MODEL_ID + "\",\n" + " \"name\": \"" + MODEL_INDEX + "\"\n" + " }\n" + " }" + "}"); client().performRequest(request); } private void startDeployment() throws IOException { Request request = new Request("POST", "/_ml/trained_models/" + MODEL_ID + "/deployment/_start"); Response response = client().performRequest(request); logger.info("Start response: " + EntityUtils.toString(response.getEntity())); } private void stopDeployment() throws IOException { Request request = new Request("POST", "/_ml/trained_models/" + MODEL_ID + "/deployment/_stop"); client().performRequest(request); } private Response infer(String input) throws IOException { Request request = new Request("POST", "/_ml/trained_models/" + MODEL_ID + "/deployment/_infer"); request.setJsonEntity("{ " + "\"input\": \"" + input + "\"\n" + "}"); return client().performRequest(request); } }
package zyx.opengl.models; import java.nio.FloatBuffer; import java.nio.IntBuffer; import org.lwjgl.opengl.*; import zyx.engine.GameEngine; import zyx.opengl.shaders.ShaderManager; import zyx.utils.cheats.Print; class ModelUtils { /** * Generates a new buffer object. For example a VBO or EBO * * @return the newly created bufferObject */ static int generateBufferObject() { return GL15.glGenBuffers(); } /** * Binds a VBO to be active * * @param vbo The VBO to bind */ static void bindBufferObject_Array(int vbo) { GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); } /** * Uploads the data to the currently bound VBO * * @param data The vertex data to upload */ static void fillVBO_Static(float[] data) { FloatBuffer buffer = BufferWrapper.toBuffer(data); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW); } /** * Uploads the data to the currently bound VBO * * @param data The vertex data to upload */ static void fillVBO_Dynamic(float[] data) { FloatBuffer buffer = BufferWrapper.toBuffer(data); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, GL15.GL_DYNAMIC_DRAW); } /** * Binds an EBO to be active * * @param ebo The EBO to bind */ static void bindBufferObject_Element(int ebo) { GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, ebo); } /** * Uploads the data to the currently bound EBO * * @param data The element data to upload */ static void fillEBO_Static(int[] data) { IntBuffer buffer = BufferWrapper.toBuffer(data); GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW); } /** * Generates a new VAO * * @return The newly created Vertex Array */ static int generateVertexArray() { return GL30.glGenVertexArrays(); } /** * Binds a VAO to be active * * @param vao The VAO to bind */ static void bindVertexArray(int vao) { GL30.glBindVertexArray(vao); } /** * Draws what the vao parameter contains with the amount of elements given * * @param vao The VAO to draw * @param elementCount How many elements the VAO contains */ static void drawElements(int vao, int elementCount) { GL30.glBindVertexArray(vao); GL11.glDrawElements(GL11.GL_TRIANGLES, elementCount, GL11.GL_UNSIGNED_INT, 0); GameEngine.drawCalls++; } /** * Draws what the vao parameter contains with the amount of elements given * * @param vao The VAO to draw * @param elementCount How many elements the VAO contains * @param instanceCount How many instances to draw */ static void drawInstancedElements(int vao, int elementCount, int instanceCount) { GL30.glBindVertexArray(vao); GL31.glDrawElementsInstanced(GL11.GL_TRIANGLES, elementCount, GL11.GL_UNSIGNED_INT, 0, instanceCount); GameEngine.drawCalls++; } static int addAttribute(int shaderProgram, String attributeName, int components, int stride, int offset) { int positionAttrib = GL20.glGetAttribLocation(shaderProgram, attributeName); if (positionAttrib >= 0) { GL20.glEnableVertexAttribArray(positionAttrib); GL20.glVertexAttribPointer(positionAttrib, components, GL11.GL_FLOAT, false, Float.BYTES * stride, Float.BYTES * offset); } else { String msg = "[Warning] Vertex attribute \"%s\" was not found in %s - (It might be unused)"; String shader = ShaderManager.INSTANCE.getNameFromProgram(shaderProgram); Print.out(String.format(msg, attributeName, shader)); } return positionAttrib; } static void addInstanceAttribute(int shaderProgram, String attributeName, int components, int stride, int offset) { int positionAttrib = addAttribute(shaderProgram, attributeName, components, stride, offset); if (positionAttrib >= 0) { GL33.glVertexAttribDivisor(positionAttrib, 1); } } // static void disposeModel(int vao, int vbo, int ebo) // GL15.glDeleteBuffers(vbo); // GL15.glDeleteBuffers(ebo); // GL30.glDeleteVertexArrays(vao); static void disposeBuffer(int buffer) { GL15.glDeleteBuffers(buffer); } static void disposeVertexArray(int vao) { GL30.glDeleteVertexArrays(vao); } }
package controllers; import java.util.Map; import models.Surfer; import play.data.Form; import play.mvc.Controller; import play.mvc.Result; import play.mvc.Security; import views.formdata.CountryTypes; import views.formdata.FootstyleTypes; import views.formdata.SearchForm; import views.formdata.SurferForm; import views.formdata.SurferTypes; import views.html.Index; import views.html.ManageSurfer; import views.html.ShowSurfer; import views.html.SurferList; /** * Implements the surfer controllers for this application. */ public class Surfers extends Controller{ private static final Form<SearchForm> searchForm = Form.form(SearchForm.class); private static final Form<SurferForm> surferForm = Form.form(SurferForm.class); /** * Gets all surfers. * @return The resulting home page. */ public static Result index(int page, String name, String country, String surferType) { return ok(SurferList.render("Surfer List", Secured.isLoggedIn(ctx()), Secured.getUserInfo(ctx()), Surfer.page(5,page,name,country,surferType), SurferTypes.getTypes(), CountryTypes.getCountryTypes(), searchForm)); } /** * Gets an existing surfer's page. * @return The surfer's page. */ public static Result getSurfer(String slug) { return ok(ShowSurfer.render("Surfer", Secured.isLoggedIn(ctx()), Secured.getUserInfo(ctx()), Surfer.getSurfer(slug), SurferTypes.getTypes(), CountryTypes.getCountryTypes(), searchForm)); } /** * Creates a new surfer's page. * @return The new surfer form. */ @Security.Authenticated(Secured.class) public static Result newSurfer() { Form<SurferForm> filledSurferForm = surferForm.fill(new SurferForm()); return ok(ManageSurfer.render("New", Secured.isLoggedIn(ctx()), Secured.getUserInfo(ctx()), filledSurferForm, FootstyleTypes.getFootStyleTypes(), SurferTypes.getTypes(), CountryTypes.getCountryTypes(), searchForm)); } /** * Deletes a surfer's page. * @return The resulting home page. */ @Security.Authenticated(Secured.class) public static Result deleteSurfer(String slug) { Surfer.deleteSurfer(slug); return ok(Index.render("Home", Secured.isLoggedIn(ctx()), Secured.getUserInfo(ctx()), Surfer.getRandomSurfers(3), SurferTypes.getTypes(), CountryTypes.getCountryTypes(), searchForm)); } /** * Edit a surfer's page. * @return The edit surfer form. */ @Security.Authenticated(Secured.class) public static Result manageSurfer(String slug) { SurferForm data = new SurferForm(Surfer.getSurfer(slug),true); Form<SurferForm> filledSurferForm = surferForm.fill(data); Map<String, Boolean> filledSurferTypeMap = SurferTypes.getTypes(data.type); return ok(ManageSurfer.render("Manage", Secured.isLoggedIn(ctx()), Secured.getUserInfo(ctx()), filledSurferForm, FootstyleTypes.getFootStyleTypes(), filledSurferTypeMap, CountryTypes.getCountryTypes(), searchForm)); } /** * Post a surfer's page. * @return The resulting home page, or edit form on error. */ @Security.Authenticated(Secured.class) public static Result postSurfer() { Form<SurferForm> filledSurferForm = surferForm.bindFromRequest(); String type = filledSurferForm.data().get("type"); if (filledSurferForm.hasErrors()) { return badRequest(ManageSurfer.render("Manage", Secured.isLoggedIn(ctx()), Secured.getUserInfo(ctx()), filledSurferForm, FootstyleTypes.getFootStyleTypes(), SurferTypes.getTypes(type), CountryTypes.getCountryTypes(), searchForm)); } else { SurferForm data = filledSurferForm.get(); Surfer.addSurfer(data); return redirect(routes.Application.index()); } } /** * Searches for surfers. * @return The resulting list of surfers who satisfy the search. */ public static Result surferSearch() { Form<SearchForm> formData = searchForm.bindFromRequest(); SearchForm data = formData.get(); return ok(SurferList.render("Search", Secured.isLoggedIn(ctx()), Secured.getUserInfo(ctx()), Surfer.page(5, 0, data.name, data.country, data.surferType), SurferTypes.getTypes(), CountryTypes.getCountryTypes(), searchForm)); } }
/** * @author UCSD MOOC development team and YOU * * A class which reprsents a graph of geographic locations * Nodes in the graph are intersections between * */ package roadgraph; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.function.Consumer; import geography.GeographicPoint; import util.GraphLoader; /** * @author UCSD MOOC development team and YOU * * A class which represents a graph of geographic locations * Nodes in the graph are intersections between * */ public class MapGraph { /* Use a Adjacency List to hold the graph */ private Map<GeographicPoint, ArrayList<Edge>> adjLst; private int numVertices, numEdges; /** * Create a new empty MapGraph */ public MapGraph() { adjLst = new HashMap<GeographicPoint, ArrayList<Edge>>(); } /** * Get the number of vertices (road intersections) in the graph * @return The number of vertices in the graph. */ public int getNumVertices() { return numVertices; } /** * Return the intersections, which are the vertices in this graph. * @return The vertices in this graph as GeographicPoints */ public Set<GeographicPoint> getVertices() { /* Return a copy of the set of vertices. We this in order to * not expose the internals of our graph to the outside world */ return new HashSet<GeographicPoint>(adjLst.keySet()); } /** * Get the number of road segments in the graph * @return The number of edges in the graph. */ public int getNumEdges() { return numEdges; } /** * Helper method to check if a given vertex exists in the graph */ private boolean hasVertex(GeographicPoint location) { return adjLst.keySet().contains(location); } /** Add a node corresponding to an intersection at a Geographic Point * If the location is already in the graph or null, this method does * not change the graph. * @param location The location of the intersection * @return true if a node was added, false if it was not (the node * was already in the graph, or the parameter is null). */ public boolean addVertex(GeographicPoint location) { /* Check if the vertex was already in * the graph, or the parameter is null */ if ((location == null) || hasVertex(location)) return false; /* Add to graph and increment number of vertices */ adjLst.put(location, new ArrayList<Edge>()); numVertices++; return true; } public void addEdge(GeographicPoint from, GeographicPoint to, String roadName, String roadType, double length) throws IllegalArgumentException { /* Check for: * 1. The points have not already been added as nodes to the graph * 2. Any of the arguments is null * 3. If the length is less than 0 */ if ((from == null) || (to == null) || (!hasVertex(to)) || (!hasVertex(from)) || (roadName == null) || (roadType == null) || (length < 0)) throw new IllegalArgumentException(); /* Create a new Edge object */ Edge e = new Edge(to.x, to.y, roadName, roadType, length); /* Add to graph and increment number of edges */ adjLst.get(from).add(e); numEdges++; } /** Find the path from start to goal using breadth first search * * @param start The starting location * @param goal The goal location * @return The list of intersections that form the shortest (unweighted) * path from start to goal (including both start and goal). */ public List<GeographicPoint> bfs(GeographicPoint start, GeographicPoint goal) { // Dummy variable for calling the search algorithms Consumer<GeographicPoint> temp = (x) -> {}; return bfs(start, goal, temp); } /** Find the path from start to goal using breadth first search * * @param start The starting location * @param goal The goal location * @param nodeSearched A hook for visualization. See assignment instructions for how to use it. * @return The list of intersections that form the shortest (unweighted) * path from start to goal (including both start and goal). */ public List<GeographicPoint> bfs(GeographicPoint start, GeographicPoint goal, Consumer<GeographicPoint> nodeSearched) { /* Check sanity of arguments */ if ((start == null) || (goal == null) || (nodeSearched == null) || (!hasVertex(start)) || (!hasVertex(goal))) return null; /* Generate the parent Map */ Map<GeographicPoint, GeographicPoint> parentMap = genParentMap(start, goal, nodeSearched); /* Generate the route based on the parent Map */ return generateRoute(parentMap, start, goal); } /** Find the path from start to goal using Dijkstra's algorithm * * @param start The starting location * @param goal The goal location * @return The list of intersections that form the shortest path from * start to goal (including both start and goal). */ public List<GeographicPoint> dijkstra(GeographicPoint start, GeographicPoint goal) { // Dummy variable for calling the search algorithms // You do not need to change this method. Consumer<GeographicPoint> temp = (x) -> {}; return dijkstra(start, goal, temp); } /** Find the path from start to goal using Dijkstra's algorithm * * @param start The starting location * @param goal The goal location * @param nodeSearched A hook for visualization. See assignment instructions for how to use it. * @return The list of intersections that form the shortest path from * start to goal (including both start and goal). */ public List<GeographicPoint> dijkstra(GeographicPoint start, GeographicPoint goal, Consumer<GeographicPoint> nodeSearched) { // TODO: Implement this method in WEEK 3 // Hook for visualization. See writeup. //nodeSearched.accept(next.getLocation()); return null; } /** Find the path from start to goal using A-Star search * * @param start The starting location * @param goal The goal location * @return The list of intersections that form the shortest path from * start to goal (including both start and goal). */ public List<GeographicPoint> aStarSearch(GeographicPoint start, GeographicPoint goal) { // Dummy variable for calling the search algorithms Consumer<GeographicPoint> temp = (x) -> {}; return aStarSearch(start, goal, temp); } /** Find the path from start to goal using A-Star search * * @param start The starting location * @param goal The goal location * @param nodeSearched A hook for visualization. See assignment instructions for how to use it. * @return The list of intersections that form the shortest path from * start to goal (including both start and goal). */ public List<GeographicPoint> aStarSearch(GeographicPoint start, GeographicPoint goal, Consumer<GeographicPoint> nodeSearched) { // TODO: Implement this method in WEEK 3 // Hook for visualization. See writeup. //nodeSearched.accept(next.getLocation()); return null; } @Override public String toString() { StringBuilder sb = new StringBuilder("This is a Graph with " + getNumVertices() + " vertices and " + getNumEdges() + " edges."); sb.append("\n"); Set<GeographicPoint> nodeSet = adjLst.keySet(); for (GeographicPoint g : nodeSet) { sb.append(g); sb.append("->"); sb.append("{"); ArrayList<Edge> lst = adjLst.get(g); for (Edge j : lst) sb.append(j + "| "); sb.deleteCharAt(sb.length() - 1); sb.deleteCharAt(sb.length() - 1); sb.append("}\n"); } return sb.toString(); } /** * Helper function to get the neighbors for a given GeographicPoint */ private List<GeographicPoint> getNeighbors(GeographicPoint v) { return new ArrayList<GeographicPoint>(adjLst.get(v)); } /** * Helper function to do the core work of the BFS algorithm * and generate the parent map. */ private Map<GeographicPoint, GeographicPoint> genParentMap(GeographicPoint start, GeographicPoint goal, Consumer<GeographicPoint> nodeSearched) { /* Initialize all the data structures needed for BFS */ Queue<GeographicPoint> q = new LinkedList<GeographicPoint>(); Set<GeographicPoint> visited = new HashSet<GeographicPoint>(); Map<GeographicPoint, GeographicPoint> parentMap = new HashMap<GeographicPoint, GeographicPoint>(); /* Add the starting node to the queue and mark it visited */ q.add(start); visited.add(start); /* Keep running till the queue becomes empty */ while (!q.isEmpty()) { GeographicPoint cur = q.remove(); /* Report searched node to the consumer */ nodeSearched.accept(cur); if (cur.equals(goal)) { break; } /* Add every non-visited neighbor to the visited * list, the queue and the parent map */ List<GeographicPoint> neighbors = getNeighbors(cur); for (GeographicPoint n : neighbors) { if (!visited.contains(n)) { visited.add(n); q.add(n); parentMap.put(n, cur); } } } return parentMap; } /** * Helper function to generate the route based on the parent map */ private List<GeographicPoint> generateRoute( Map<GeographicPoint, GeographicPoint> parentMap, GeographicPoint start, GeographicPoint goal) { List<GeographicPoint> route = new ArrayList<GeographicPoint>(); /* Generate the path list by looking up in the parent map */ route.add(0, goal); GeographicPoint node = goal; while (!node.equals(start)) { node = parentMap.get(node); /* No path exists from start to goal */ if (node == null) return null; route.add(0, node); } return route; } public static void main(String[] args) { System.out.print("Making a new map..."); MapGraph theMap = new MapGraph(); System.out.print("DONE. \nLoading the map..."); GraphLoader.loadRoadMap("data/testdata/simpletest.map", theMap); System.out.println("DONE."); System.out.println(theMap); List<GeographicPoint> path = theMap.bfs(new GeographicPoint(8,-1), new GeographicPoint(8, -1)); for (GeographicPoint p : path) { System.out.println(p); } // You can use this method for testing. /* Use this code in Week 3 End of Week Quiz MapGraph theMap = new MapGraph(); System.out.print("DONE. \nLoading the map..."); GraphLoader.loadRoadMap("data/maps/utc.map", theMap); System.out.println("DONE."); GeographicPoint start = new GeographicPoint(32.868629, -117.215393); GeographicPoint end = new GeographicPoint(32.868629, -117.215393); List<GeographicPoint> route = theMap.dijkstra(start,end); List<GeographicPoint> route2 = theMap.aStarSearch(start,end); */ } }
package models; import com.avaje.ebean.Ebean; import com.avaje.ebean.ExpressionList; import com.avaje.ebean.Page; import com.avaje.ebean.RawSqlBuilder; import models.enumeration.ProjectScope; import models.enumeration.RequestState; import models.enumeration.ResourceType; import models.enumeration.RoleType; import models.resource.GlobalResource; import models.resource.Resource; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.NoHeadException; import org.joda.time.DateTime; import org.joda.time.Duration; import org.tmatesoft.svn.core.SVNException; import play.data.validation.Constraints; import play.db.ebean.Model; import play.db.ebean.Transactional; import playRepository.*; import utils.CacheStore; import utils.FileUtil; import utils.JodaDateUtil; import validation.ExConstraints; import javax.annotation.Nonnull; import javax.persistence.*; import javax.servlet.ServletException; import java.io.IOException; import java.util.*; import static utils.CacheStore.getProjectCacheKey; import static utils.CacheStore.projectMap; import static utils.HttpUtil.decodeUrlString; @Entity public class Project extends Model implements LabelOwner { private static final long serialVersionUID = 1L; public static final play.db.ebean.Model.Finder <Long, Project> find = new Finder<>(Long.class, Project.class); private static final int DRAFT_TIME_IN_MILLIS = 1000 * 60 * 60; @Id public Long id; @Constraints.Required @Constraints.Pattern("^[a-zA-Z0-9-_\\.-]+$") @ExConstraints.Restricted({".", "..", ".git"}) public String name; public String overview; public String vcs; public String siteurl; public String owner; public Date createdDate; @OneToMany(mappedBy = "project", cascade = CascadeType.ALL) public Set<Issue> issues; @OneToMany(mappedBy = "project", cascade = CascadeType.ALL) public List<ProjectUser> projectUser; @OneToMany(mappedBy = "project", cascade = CascadeType.ALL) public List<Posting> posts; @OneToMany(mappedBy = "project", cascade = CascadeType.ALL) public List<Milestone> milestones; /** Project Notification */ @OneToMany(mappedBy = "project", cascade = CascadeType.ALL) public List<UserProjectNotification> notifications; private long lastIssueNumber; private long lastPostingNumber; public boolean isCodeAccessibleMemberOnly; @ManyToMany public Set<Label> labels; @ManyToOne public Project originalProject; @OneToMany(mappedBy = "originalProject") public List<Project> forkingProjects; @OneToMany(mappedBy = "project") public Set<Webhook> webhooks; @OneToMany(mappedBy = "project") public Set<Assignee> assignees; public Date lastPushedDate; @OneToMany(mappedBy = "project", cascade = CascadeType.ALL) public List<PushedBranch> pushedBranches; @ManyToMany(mappedBy = "enrolledProjects") public List<User> enrolledUsers; @OneToMany(cascade = CascadeType.REMOVE) public List<CommitComment> codeComments; @OneToMany(cascade = CascadeType.REMOVE) public List<CommentThread> commentThreads; public Integer defaultReviewerCount = 1; public boolean isUsingReviewerCount; @ManyToOne public Organization organization; @Enumerated(EnumType.STRING) public ProjectScope projectScope; @OneToOne(mappedBy = "project", cascade = CascadeType.ALL) public ProjectMenuSetting menuSetting; private String previousOwnerLoginId; private String previousName; private Long previousNameChangedTime; @OneToMany(mappedBy = "project", cascade = CascadeType.ALL) public List<IssueLabel> issueLabels; /** * @see {@link User#SITE_MANAGER_ID} * @see {@link RoleType#SITEMANAGER} */ public static Long create(Project newProject) { newProject.siteurl = "http://localhost:9000/" + newProject.name; newProject.createdDate = new Date(); newProject.save(); ProjectUser.assignRole(User.SITE_MANAGER_ID, newProject.id, RoleType.SITEMANAGER); return newProject.id; } public static Page<Project> findByName(String name, int pageSize, int pageNum) { if(StringUtils.isBlank(name)){ return find.where().order().desc("createdDate").findPagingList(pageSize).getPage(pageNum); } return find.where().ilike("name", "%" + decodeUrlString(name) + "%") .findPagingList(pageSize).getPage(pageNum); } public static Project findByOwnerAndProjectName(String loginId, String projectName) { String key = getProjectCacheKey(loginId, projectName); Long projectId = CacheStore.projectMap.get(key); if(projectId == null || projectId == 0){ Project project= find.where().ieq("owner", decodeUrlString(loginId)).ieq("name", decodeUrlString(projectName)) .findUnique(); if(project != null){ CacheStore.projectMap.put(key, project.id); } return project; } else { return find.byId(projectId); } } public Set<User> findAuthors() { Set<User> allAuthors = new LinkedHashSet<>(); allAuthors.addAll(getIssueUsers()); allAuthors.addAll(getPostingUsers()); allAuthors.addAll(getPullRequestUsers()); return allAuthors; } public Set<User> findAuthorsAndWatchers() { Set<User> allAuthors = new LinkedHashSet<>(); allAuthors.addAll(findAuthors()); allAuthors.addAll(getWatchedUsers()); return allAuthors; } private Set<User> getIssueUsers() { String issueSql = "SELECT distinct author_id id FROM ISSUE where project_id=" + this.id; return User.find.setRawSql(RawSqlBuilder.parse(issueSql).create()).findSet(); } private Set<User> getPostingUsers() { String postSql = "SELECT distinct author_id id FROM posting where project_id=" + this.id; return User.find.setRawSql(RawSqlBuilder.parse(postSql).create()).findSet(); } private Set<User> getPullRequestUsers() { String postSql = "SELECT distinct contributor_id id FROM pull_request where to_project_id=" + this.id; return User.find.setRawSql(RawSqlBuilder.parse(postSql).create()).findSet(); } public Set<User> getWatchedUsers() { String postSql = "SELECT distinct user_id id FROM watch where resource_type='PROJECT' and resource_id=" + this.id; return User.find.setRawSql(RawSqlBuilder.parse(postSql).create()).findSet(); } public boolean hasMember(User user) { if (user.isMemberOf(this) || user.isManagerOf(this) || user.isSiteManager()) { return true; } else { return false; } } public static boolean exists(String loginId, String projectName) { int findRowCount = find.where().ieq("owner", loginId) .ieq("name", projectName).findRowCount(); return (findRowCount != 0); } public static boolean projectNameChangeable(Long id, String userName, String projectName) { int findRowCount = find.where().ieq("name", decodeUrlString(projectName)) .ieq("owner", userName).ne("id", id).findRowCount(); return (findRowCount == 0); } /** * @see {@link RoleType#MANAGER} */ public static boolean isOnlyManager(Long userId) { List<Project> projects = find.select("id").select("name").where() .eq("projectUser.user.id", userId) .eq("projectUser.role.id", RoleType.MANAGER.roleType()) .findList(); for (Project project : projects) { if (ProjectUser.checkOneMangerPerOneProject(userId, project.id)) { return true; } } return false; } public static List<Project> findProjectsByMember(Long userId) { return find.where().eq("projectUser.user.id", userId).findList(); } public static List<Project> findProjectsJustMemberAndNotOwner(User user) { return findProjectsJustMemberAndNotOwner(user, null); } public static List<Project> findProjectsJustMemberAndNotOwner(User user, String orderString) { ExpressionList<Project> el = find.where() .eq("projectUser.user.id", user.id) .ne("projectUser.role.id", RoleType.SITEMANAGER.roleType()) .ne("owner", user.loginId); if (StringUtils.isNotBlank(orderString)) { el.orderBy(orderString); } return el.findList(); } public static List<Project> findProjectsByMemberWithFilter(Long userId, String orderString) { List<Project> userProjectList = find.where().eq("projectUser.user.id", userId).findList(); if( orderString == null ){ return userProjectList; } return Ebean.filter(Project.class).sort(orderString).filter(userProjectList); } public static List<Project> findProjectsCreatedByUser(String loginId, String orderString) { if( orderString == null ){ return find.where().eq("owner", loginId).orderBy("createdDate desc").findList(); } else { return find.where().eq("owner", loginId).orderBy(orderString).findList(); } } public static List<Project> findProjectsCreatedByUserAndScope(String loginId, ProjectScope projectScope, String orderString) { return find.where().eq("owner", loginId) .eq("projectScope", projectScope) .orderBy(orderString).findList(); } public Date lastUpdateDate() { try { PlayRepository repository = RepositoryService.getRepository(this); List<String> branches = repository.getRefNames(); if (!branches.isEmpty() && repository instanceof GitRepository) { GitRepository gitRepo = new GitRepository(owner, name); List<Commit> history = gitRepo.getHistory(0, 2, "HEAD", null); if(history == null) { return this.createdDate; } return history.get(0).getAuthorDate(); } } catch (IOException e) { e.printStackTrace(); } catch (NoHeadException e) { e.printStackTrace(); } catch (GitAPIException e) { e.printStackTrace(); } catch (UnsupportedOperationException e) { e.printStackTrace(); } catch (ServletException e) { e.printStackTrace(); } return this.createdDate; } public String defaultBranch() { try { return RepositoryService.getRepository(this).getDefaultBranch(); } catch (Exception ignored) { } return "HEAD"; } public Duration ago() { return JodaDateUtil.ago(lastUpdateDate()); } public Duration lastPushedDateAgo(){ if( this.lastPushedDate == null){ return null; } return JodaDateUtil.ago(this.lastPushedDate); } public String readme() { try { byte[] bytes = RepositoryService.getRepository(this) .getRawFile("HEAD", getReadmeFileName()); return new String(bytes, FileUtil.detectCharset(bytes)); } catch (Exception e) { return null; } } public String getIssueTemplate() { try { byte[] bytes = RepositoryService.getRepository(this) .getRawFile("HEAD", "ISSUE_TEMPLATE.md"); return new String(bytes, FileUtil.detectCharset(bytes)); } catch (Exception e) { return null; } } /** * @return the readme file name or {@code null} if the file does not exist * @throws IOException Signals that an I/O exception has occurred. * @throws GitAPIException the git api exception * @throws SVNException the sVN exception * @throws ServletException the servlet exception */ public String getReadmeFileName() throws IOException, SVNException, ServletException { String baseFileName = "README.md"; PlayRepository repo = RepositoryService.getRepository(this); if (repo.isFile(baseFileName)) { return baseFileName; } if (repo.isFile(baseFileName.toLowerCase())) { return baseFileName.toLowerCase(); } if(repo instanceof SVNRepository) { baseFileName = "/trunk/" + baseFileName; if(repo.isFile(baseFileName)) { return baseFileName; } baseFileName = baseFileName.toLowerCase(); if(repo.isFile(baseFileName)) { return baseFileName; } } return null; } private boolean isLastIssueNumberCorrect() { return issues == null || lastIssueNumber >= issues.size(); } private Long getLastIssueNumber() { if (isLastIssueNumberCorrect()) { return lastIssueNumber; } Issue issue = Issue.finder.where().eq("project.id", id).order().desc("number").findList().get(0); issue.refresh(); return issue.number == null ? 0L : issue.number; } private void setLastIssueNumber(Long number) { lastIssueNumber = number; } private boolean isLastPostingNumberCorrect() { return posts == null || lastPostingNumber >= posts.size(); } private Long getLastPostingNumber() { if (isLastPostingNumberCorrect()) { return lastPostingNumber; } Posting posting = Posting.finder.where().eq("project.id", id).order().desc("number").findList().get(0); posting.refresh(); return posting.number == null ? 0L : posting.number; } private void setLastPostingNumber(Long number) { lastPostingNumber = number; } /** * . * * . * * @return {@code lastIssueNumber} */ public static Long increaseLastIssueNumber(Long projectId) { Project project = find.byId(projectId); project.setLastIssueNumber(project.getLastIssueNumber() + 1); project.update(); return project.lastIssueNumber; } public static void fixLastIssueNumber(Long projectId) { Project project = find.byId(projectId); project.refresh(); project.setLastIssueNumber(project.getLastIssueNumber()); project.update(); } public static Long increaseLastPostingNumber(Long projectId) { Project project = find.byId(projectId); project.setLastPostingNumber(project.getLastPostingNumber() + 1); project.update(); return project.lastPostingNumber; } public static void fixLastPostingNumber(Long projectId) { Project project = find.byId(projectId); project.refresh(); project.setLastPostingNumber(project.getLastPostingNumber()); project.update(); } public Resource labelsAsResource() { return new Resource() { @Override public String getId() { return id.toString(); } @Override public Project getProject() { return Project.this; } @Override public ResourceType getType() { return ResourceType.PROJECT_LABELS; } }; } @Override public Resource asResource() { return new GlobalResource() { @Override public String getId() { return id.toString(); } @Override public ResourceType getType() { return ResourceType.PROJECT; } @Override public Project getProject() { return Project.this; } }; } public User getOwnerByLoginId(String loginId){ return User.findByLoginId(loginId); } public Boolean attachLabel(Label label) { if (label.projects.contains(this)) { // Return false if the label has been already attached. return false; } // Attach new label. I don't know why labels.add(label) does not work. label.projects.add(this); label.update(); return true; } public void detachLabel(Label label) { label.projects.remove(this); if (label.projects.size() == 0) { label.delete(); } else { label.update(); } } public boolean isOwner(User user) { return owner.toLowerCase().equals(user.loginId.toLowerCase()); } public String toString() { return owner + "/" + name; } public List<ProjectUser> members() { return ProjectUser.findMemberListByProject(this.id); } /** * Return assignable users to this project and group of the project. * * If the project has no groups, it returns all project members. * If the project has a group and is private, it returns all project members and group admins. * If the project has a group and is protected or public, it returns all project and group members. */ public List<User> getAssignableUsers() { return User.findUsersByProjectAndOrganization(this); } public List<User> getAssignableUsersAndAssignee(Issue issue) { List<User> users = getAssignableUsers(); if (issue != null && issue.assignee != null && !users.contains(issue.assignee.user)) { users.add(issue.assignee.user); } return users; } public boolean isProjectOrOrganizationUser(User user) { return User.findUsersByProjectAndOrganization(this).contains(user); } public boolean isAssignableUser(User user) { return getAssignableUsers().contains(user); } public boolean isForkedFromOrigin() { return this.originalProject != null; } public boolean hasForks() { return this.forkingProjects.size() > 0; } public List<Project> getForkingProjects() { if(this.forkingProjects == null) { this.forkingProjects = new ArrayList<>(); } return forkingProjects; } public void addFork(Project forkProject) { getForkingProjects().add(forkProject); forkProject.originalProject = this; } public static List<Project> findByOwnerAndOriginalProject(String loginId, Project originalProject) { return find.where() .eq("originalProject", originalProject) .eq("owner", loginId) .findList(); } public void deleteFork() { if(this.originalProject != null) { this.originalProject.deleteFork(this); } } private void deleteFork(Project project) { getForkingProjects().remove(project); project.originalProject = null; } public void fixInvalidForkData() { if(originalProject != null) { try { String owner = originalProject.owner; } catch (EntityNotFoundException e) { originalProject = null; super.update(); } } } /** * @see controllers.ProjectApp#members(String, String) */ @Transactional public void cleanEnrolledUsers() { List<User> enrolledUsers = this.enrolledUsers; List<User> acceptedUsers = new ArrayList<>(); List<ProjectUser> members = this.members(); for(ProjectUser projectUser : members) { User user = projectUser.user; if(enrolledUsers.contains(user)) { acceptedUsers.add(user); } } for(User user : acceptedUsers) { user.cancelEnroll(this); NotificationEvent.afterMemberRequest(this, user, RequestState.ACCEPT); } } public void changeVCS() throws Exception { if(this.forkingProjects != null) { for(Project fork : forkingProjects) { fork.originalProject = null; fork.update(); } } RepositoryService.deleteRepository(this); this.vcs = nextVCS(); RepositoryService.getRepository(this).create(); this.update(); } public boolean isCodeAvailable() { return menuSetting == null || menuSetting.code; } /** * When a project is renamed or transferred, record it's previous location and change time * * @param project */ public void recordRenameOrTransferHistoryIfLastChangePassed24HoursFrom(@Nonnull Project project) { if(isRenamedOrTransferredIn24Hours(project)) { this.previousNameChangedTime = DateTime.now().getMillis(); this.previousName = project.name; this.previousOwnerLoginId = project.owner; } } private static boolean isRenamedOrTransferredIn24Hours(@Nonnull Project project) { return project.previousNameChangedTime == null || hasPassed24hoursFrom(project.previousNameChangedTime); } private static boolean hasPassed24hoursFrom(Long time) { return new Duration(DateTime.now().getMillis() - time).getStandardHours() > 24; } public enum State { PUBLIC, PRIVATE, ALL } @Override public void delete() { CacheStore.refreshProjectMap(); projectMap.remove(getProjectCacheKey(this.owner, this.name)); deleteProjectTransfer(); deleteFork(); deleteCommentThreads(); deletePullRequests(); if(this.hasForks()) { for(Project fork : forkingProjects) { fork.deletePullRequests(); fork.deleteOriginal(); fork.update(); } } // Issues must be deleted before issue labels because issues may refer // issue labels. for(Issue issue : issues) { issue.delete(); } for(IssueLabelCategory category : IssueLabelCategory.findByProject(this)) { category.delete(); } for (Assignee assignee : assignees) { assignee.delete(); } for (Webhook webhook : webhooks) { webhook.delete(); } for(Posting posting : posts) { posting.delete(); } for (Label label : labels) { label.delete(this); label.update(); } super.delete(); } private void deleteProjectTransfer() { List<ProjectTransfer> pts = ProjectTransfer.findByProject(this); for(ProjectTransfer pt : pts) { pt.delete(); } } private void deleteOriginal() { this.originalProject = null; } private void deletePullRequests() { List<PullRequest> sentPullRequests = PullRequest.findSentPullRequests(this); for(PullRequest pullRequest : sentPullRequests) { CommentThread.deleteByPullRequest(pullRequest); pullRequest.delete(); } List<PullRequest> allReceivedRequests = PullRequest.allReceivedRequests(this); for(PullRequest pullRequest : allReceivedRequests) { CommentThread.deleteByPullRequest(pullRequest); pullRequest.delete(); } } private void deleteCommentThreads() { for(CommentThread commentThread : this.commentThreads) { commentThread.delete(); } } public static String newProjectName(String loginId, String projectName) { Project project = Project.findByOwnerAndProjectName(loginId, projectName); if(project == null) { return projectName; } for(int i = 1 ; ; i++) { String newProjectName = projectName + "-" + i; project = Project.findByOwnerAndProjectName(loginId, newProjectName); if(project == null) { return newProjectName; } } } /** * @see #newProjectName(String, String) */ public static Project copy(Project project, String owner) { Project copyProject = new Project(); copyProject.name = newProjectName(owner, project.name); copyProject.overview = project.overview; copyProject.vcs = project.vcs; copyProject.owner = owner; copyProject.projectScope = project.projectScope; copyProject.menuSetting = new ProjectMenuSetting(project.menuSetting); copyProject.menuSetting.project = copyProject; copyProject.menuSetting.save(); return copyProject; } @Override public Set<Label> getLabels() { return labels; } public static int countProjectsJustMemberAndNotOwner(String loginId) { return find.where().eq("projectUser.user.loginId", loginId) .ne("owner", loginId).findRowCount(); } public static int countProjectsCreatedByUser(String loginId) { return find.where().eq("owner", loginId).findRowCount(); } public List<PushedBranch> getRecentlyPushedBranches() { return PushedBranch.find.where() .eq("project", this) .gt("pushedDate", DateTime.now().minusMillis(DRAFT_TIME_IN_MILLIS).toDate()) .findList(); } public List<PushedBranch> getOldPushedBranches() { return PushedBranch.find.where() .eq("project", this) .lt("pushedDate", DateTime.now().minusMillis(DRAFT_TIME_IN_MILLIS).toDate()) .findList(); } public boolean isGit() { return vcs.equals("GIT"); } public List<Project> getAssociationProjects() { List<Project> projects = new ArrayList<>(); projects.add(this); projects.addAll(forkingProjects); if(isForkedFromOrigin() && originalProject.menuSetting.code && originalProject.menuSetting.pullRequest) { projects.add(originalProject); } return projects; } public int getMaxNumberOfRequiredReviewerCount() { List<ProjectUser> members = ProjectUser.findMemberListByProject(this.id); if(members.size() > 1) { return members.size(); } else { return 1; } } public int getWatchingCount() { Resource resource = this.asResource(); return Watch.countBy(resource.getType(), resource.getId()); } public boolean hasGroup() { return this.organization != null; } public boolean isPublic() { return projectScope == ProjectScope.PUBLIC; } public boolean isProtected() { return projectScope == ProjectScope.PROTECTED; } public boolean isPrivate() { return projectScope == ProjectScope.PRIVATE; } public String nextVCS() { if(this.vcs.equals(RepositoryService.VCS_GIT)) { return RepositoryService.VCS_SUBVERSION; } else { return RepositoryService.VCS_GIT; } } /** * Find project with previous owner and previous project name * * when to use: * When specific project can't be found. * * In some cases, it is reasonable to assume that project was moved or transferred. * In that case, try this method. * * This method is intended to be used at controllers. * * @param previousOwnerLoginid * @param previousName * @return */ public static Project findByPreviousPlaceOf(String previousOwnerLoginid, String previousName) { List<Project> projects = find.where().ieq("previousOwnerLoginId", previousOwnerLoginid).ieq("previousName", previousName) .setOrderBy("previousNameChangedTime desc").findList(); if(CollectionUtils.isEmpty(projects)){ return null; } return projects.get(0); // Choose latest } public boolean hasOldPlace(){ if(StringUtils.isBlank(this.previousName)){ return false; } else { return true; } } public String getOldPlace(){ if(this.previousOwnerLoginId == null){ return ""; } if(hasOldPlace()){ return this.previousOwnerLoginId + "/" + this.previousName; } else { return ""; } } }
package vue.Jeu; import controleur.Camera; import controleur.ControlleurEnnemi; import controleur.ControlleurPersonnage; import controleur.ControlleurSouris; import controleur.Informateur; import java.util.ArrayList; import modele.Entrepot; import org.lwjgl.util.Point; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; import vue.Hud.Hud; /** * * @author Christopher Desrosiers Mondor */ public class Game extends BasicGameState { // Donnees membres private GameContainer container; private Carte cartePrincipale; private StateBasedGame game; // Controlleurs (ecouteurs) private ControlleurSouris ecoSouris; // Camera private Camera camera; // Entrepot private Entrepot entrepot; private ArrayList personnages = new ArrayList(); private ArrayList ennemis = new ArrayList(); private ArrayList batiments = new ArrayList(); // Planche de jeu private Game cettePlanche; // Hud private Hud hud; //Menu In game private MenuIG menuIG; //Condition pour afficher menu private boolean escapePressed = false; public static int ID = 1,condi=1,tempsDeJeu=0; private float distance = 0; private Ennemi nEnnemi; // Constructeur public Game() { super(); cartePrincipale = new Carte(); personnages.add(new Joueur(cartePrincipale)); ennemis.add(new Ennemi(cartePrincipale)); cettePlanche = this; camera = new Camera(cartePrincipale); } // Methodes specifiques // Accesseur \ Mutateur public GameContainer getContainer() { return this.container; } public Camera getCamera() { return this.camera; } public ArrayList<Joueur> getPersonnages() { return this.personnages; } public Carte getCartePrincipale() { return this.cartePrincipale; } public Entrepot getEntrepot() { return this.entrepot; } public Hud getHud() { return this.hud; } public ArrayList getBatiments() { return this.batiments; } public void ajouterBatiment(Batiment unBatiment) { this.batiments.add(unBatiment); } @Override public int getID() { return this.ID; } @Override public void init(GameContainer container, StateBasedGame sbg) throws SlickException { // Jeu et carte this.container = container; this.game = sbg; //Image curseur = new Image("images/curseur.png", true); //this.container.setMouseCursor(curseur, 0, 0); this.cartePrincipale.init(); // Personnage for (Object j : personnages) { Joueur unJoueur = (Joueur) j; unJoueur.init(); unJoueur.setX(container.getWidth() / 2 + 50 * personnages.indexOf(j)); unJoueur.setY(container.getHeight() / 2 + 50 * personnages.indexOf(j)); } for (Object e : ennemis) { Ennemi unEnnemi = (Ennemi) e; unEnnemi.init(); unEnnemi.setX(container.getWidth()/2 + 250 *ennemis.indexOf(e+""+1)); unEnnemi.setY(container.getHeight()/2 + 250 * ennemis.indexOf(e)); } //this.batiment.init(); // entrepot int nombreDeRessourceInitial = Entrepot.valeurInitiale; entrepot = new Entrepot(); entrepot.setBois(nombreDeRessourceInitial); entrepot.setNourriture(nombreDeRessourceInitial); entrepot.setOr(nombreDeRessourceInitial); // Hud hud = new Hud(container, camera, container); hud.init(); //ajouter le hud comme un mouseListener a la planche du jeu. container.getInput().addMouseListener(hud); // Ecouteur for (int i = 0; i < personnages.size(); i++) { container.getInput().addMouseListener(new ControlleurPersonnage((Joueur) personnages.get(i), container, camera)); } for (int i = 0; i < ennemis.size(); i++) { container.getInput().addMouseListener(new ControlleurEnnemi((Ennemi) ennemis.get(i), container, camera)); } ecoSouris = new ControlleurSouris(cettePlanche); container.getInput().addMouseListener(ecoSouris); menuIG = new MenuIG(container, camera, container); menuIG.init(); } @Override public void render(GameContainer container, StateBasedGame sbg, Graphics g) throws SlickException { this.camera.place(container, g); this.cartePrincipale.renderArrierePlan(); //this.batiment.render(g); for (Object j : personnages) { Joueur unJoueur = (Joueur) j; unJoueur.render(g); } for (Object e : ennemis) { Ennemi unEnnemi = (Ennemi) e; unEnnemi.render(g); } this.cartePrincipale.renderAvantPlan(); g.setColor(Color.yellow); g.drawOval(Informateur.getMousePosition(camera, container).x, Informateur.getMousePosition(camera, container).y, 10, 10); ecoSouris.render(container, g); this.hud.render(g); if (container.getInput().isKeyPressed(Input.KEY_ESCAPE)) { escapePressed = !escapePressed; } if (escapePressed == true) { this.menuIG.render(g); } for (Object b : batiments) { Batiment unBatiment = (Batiment) b; unBatiment.render(g); } } @Override public void update(GameContainer container, StateBasedGame sbg, int delta) throws SlickException { for (Object j : personnages) { Joueur unJoueur = (Joueur) j; unJoueur.update(delta); this.camera.update(container); for (Object e : ennemis) { Ennemi unEnnemi = (Ennemi) e; unEnnemi.update(delta, unJoueur, personnages); //this.personnage.update(delta); this.camera.update(container); //this.camera.update(container); } } if (personnages.size() > 1) { for (int i = 0; i < personnages.size(); i++) { Joueur unPersonnage, premierPersonnage; unPersonnage = (Joueur) personnages.get(i); premierPersonnage = (Joueur) personnages.get(0); if (premierPersonnage.getxDest() == unPersonnage.getxDest() //Si leur destination (x,y) est la meme, ils vont arreter avant de se rencontrer && premierPersonnage.getyDest() == unPersonnage.getyDest() && unPersonnage.getX()< premierPersonnage.getX()) { unPersonnage.setxDest((int) premierPersonnage.getxDest() - 50 * i); //Si les autres paysans sont a gauche du premier paysan, ils s'arretent a gauche } else if(premierPersonnage.getxDest() == unPersonnage.getxDest() && premierPersonnage.getyDest() == unPersonnage.getyDest() && unPersonnage.getX()> premierPersonnage.getX()) { unPersonnage.setxDest((int) premierPersonnage.getxDest() + 50 * i); //Si les autres paysans sont a droite du premier paysan, ils s'arretent a droite } } } for (Object b : batiments) { Batiment unBatiment = (Batiment) b; this.camera.update(container); unBatiment.update(this.camera.getX(), this.camera.getY()); } if(tempsDeJeu<=5010 && tempsDeJeu>=4990 && condi==1){ condi=2; nEnnemi=new Ennemi(cartePrincipale); nEnnemi.init(); nEnnemi.setX(500); nEnnemi.setY(500); ennemis.add(nEnnemi); } tempsDeJeu+=delta; if (!personnages.isEmpty() && !ennemis.isEmpty()) { for (Object e : ennemis) { Ennemi unEnnemi = (Ennemi) e; for (int i=0; i<personnages.size(); i++) { Joueur unJoueur = (Joueur) personnages.get(i); boolean contient = personnages.contains(unEnnemi); Point ennemiPos; ennemiPos = new Point((int) unEnnemi.getX(), (int) unEnnemi.getY()); Point joueurPos = new Point((int) unJoueur.getX(), (int) unJoueur.getY()); if (unEnnemi.distancePoint(ennemiPos, joueurPos) <= 30) { System.out.println("Joueur :"+ unJoueur.getHP()); unEnnemi.attaque(unJoueur, 1, tempsDeJeu); } if (unJoueur.getHP() <= 0) { personnages.remove(unJoueur); } } } } victoire(ennemis,batiments); defaite(personnages,batiments); } public void victoire(ArrayList ennemis, ArrayList batiments) { if (ennemis.isEmpty() && batiments.isEmpty()) { // game.addState(new EndGameState(null)); game.enterState(EndGameState.ID); } } public void defaite(ArrayList personnages, ArrayList batiments){ if (personnages.isEmpty()){ // game.addState(new EndGameState(null)); game.enterState(EndGameState.ID); } } public void keyReleased(int key, char c) { switch (key) { case Input.KEY_D: game.enterState(EndGameState.ID); break; case Input.KEY_A: if (!personnages.isEmpty() && !ennemis.isEmpty()) { for (Object j : personnages) { Joueur unPaysan = (Joueur) j; for (int i=0; i<ennemis.size(); i++) { Ennemi unEnnemi = (Ennemi) ennemis.get(i); boolean contient = ennemis.contains(unEnnemi); Point paysanPos; paysanPos = new Point((int) unPaysan.getX(), (int) unPaysan.getY()); Point ennemiPos = new Point((int) unEnnemi.getX(), (int) unEnnemi.getY()); if (unPaysan.isSelected() && unPaysan.distancePoint(paysanPos, ennemiPos) <= 30) { unEnnemi.removeHP(10); System.out.println("Vie restante Ennemi: " + unEnnemi.getHP()); } if (unEnnemi.getHP() <= 0) { ennemis.remove(unEnnemi); } } } } } } }
package biz.netcentric.cq.tools.actool.configreader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.Property; import javax.jcr.PropertyIterator; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.Value; import javax.jcr.ValueFormatException; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.sling.jcr.api.SlingRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.day.cq.commons.jcr.JcrConstants; import biz.netcentric.cq.tools.actool.history.AcInstallationLog; @Service @Component public class YamlMacroChildNodeObjectsProviderImpl implements YamlMacroChildNodeObjectsProvider { private static final Logger LOG = LoggerFactory.getLogger(YamlMacroChildNodeObjectsProviderImpl.class); @Reference private SlingRepository repository; @Override public List<Object> getValuesForPath(String pathOfChildrenOfClause, AcInstallationLog history, Session session) { LOG.debug("FOR Loop: Getting children for " + pathOfChildrenOfClause); List<Object> results = new ArrayList<Object>(); try { Node node = session.getNode(pathOfChildrenOfClause); NodeIterator childrenIt = node.getNodes(); while (childrenIt.hasNext()) { Node childNode = (Node) childrenIt.next(); if (childNode.getName().startsWith("jcr:") || childNode.getName().startsWith("rep:") || childNode.getName().startsWith("oak:")) { continue; } Map<String, Object> childNodeObjectForEl = new HashMap<String, Object>(); childNodeObjectForEl.put("name", childNode.getName()); childNodeObjectForEl.put("path", childNode.getPath()); childNodeObjectForEl.put("primaryType", childNode.getPrimaryNodeType().toString()); if (childNode.hasNode(JcrConstants.JCR_CONTENT)) { Node jcrContentNode = childNode.getNode(JcrConstants.JCR_CONTENT); if (jcrContentNode.hasProperty(JcrConstants.JCR_TITLE)) { childNodeObjectForEl.put("title", jcrContentNode.getProperty(JcrConstants.JCR_TITLE).getString()); } Map<String, Object> jcrContentSubNode = getValuesForNode(jcrContentNode); childNodeObjectForEl.put(JcrConstants.JCR_CONTENT, jcrContentSubNode); } results.add(childNodeObjectForEl); } } catch (PathNotFoundException e) { history.addWarning(LOG, "Path " + pathOfChildrenOfClause + " as configured for source for FOR loop does not exist! (statement skipped)"); } catch (RepositoryException e) { throw new IllegalStateException("Could not get children of path " + pathOfChildrenOfClause + ": " + e, e); } history.addMessage(LOG, "Loop for children of " + pathOfChildrenOfClause + " evaluates to " + results.size() + " children"); return results; } private Map<String, Object> getValuesForNode(Node node) throws RepositoryException { PropertyIterator propertiesIt = node.getProperties(); Map<String, Object> values = new HashMap<String, Object>(); while (propertiesIt.hasNext()) { Property prop = (Property) propertiesIt.next(); if (prop.isMultiple()) { values.put(prop.getName(), valuesToStringArr(prop.getValues())); } else { Value value = prop.getValue(); if (isIrrelevantType(value)) { continue; } String strVal = value.getString(); values.put(prop.getName(), strVal); } } NodeIterator iterator = node.getNodes(); while (iterator.hasNext()) { Node child = iterator.nextNode(); values.put(child.getName(), getValuesForNode(child)); } return values; } private boolean isIrrelevantType(Value value) { return value.getType() == PropertyType.BINARY || value.getType() == PropertyType.REFERENCE || value.getType() == PropertyType.WEAKREFERENCE; } private String[] valuesToStringArr(Value[] values) throws ValueFormatException, RepositoryException { List<String> strVals = new ArrayList<String>(); for (int i = 0; i < values.length; i++) { Value value = values[i]; if (isIrrelevantType(value)) { continue; } strVals.add(value.getString()); } return strVals.toArray(new String[strVals.size()]); } }
package org.openhab.binding.deconz.internal.netutils; import java.net.URI; import java.util.HashMap; import java.util.Map; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage; import org.eclipse.jetty.websocket.api.annotations.WebSocket; import org.eclipse.jetty.websocket.client.WebSocketClient; import org.openhab.binding.deconz.internal.dto.SensorMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; /** * Establishes and keeps a websocket connection to the deCONZ software. * * The connection is closed by deCONZ now and then and needs to be re-established. * * @author David Graeff - Initial contribution */ @WebSocket @NonNullByDefault public class WebSocketConnection { private final Logger logger = LoggerFactory.getLogger(WebSocketConnection.class); private final WebSocketClient client; private final WebSocketConnectionListener connectionListener; private final Map<String, ValueUpdateListener> valueListener = new HashMap<>(); private final Gson gson = new Gson(); private boolean connected = false; public WebSocketConnection(WebSocketConnectionListener listener, WebSocketClient client) { this.connectionListener = listener; this.client = client; } public void start(String ip) { if (connected) { return; } try { URI destUri = URI.create("ws: client.start(); logger.debug("Connecting to: {}", destUri); client.connect(this, destUri).get(); } catch (Exception e) { connectionListener.connectionError(e); } } public void close() { try { connected = false; client.stop(); } catch (Exception e) { logger.debug("Error while closing connection: {}", e); } client.destroy(); } public void registerValueListener(String sensorID, ValueUpdateListener listener) { valueListener.put(sensorID, listener); } public void unregisterValueListener(String sensorID) { valueListener.remove(sensorID); } @OnWebSocketConnect public void onConnect(Session session) { connected = true; logger.debug("Connect: {}", session.getRemoteAddress().getAddress()); connectionListener.connectionEstablished(); } @SuppressWarnings("null") @OnWebSocketMessage public void onMessage(String message) { SensorMessage changedMessage = gson.fromJson(message, SensorMessage.class); ValueUpdateListener listener = valueListener.get(changedMessage.id); if (listener != null) { listener.valueUpdated(changedMessage.id, changedMessage.state); } } @OnWebSocketError public void onError(Throwable cause) { connected = false; connectionListener.connectionError(cause); } @OnWebSocketClose public void onClose(int statusCode, String reason) { connected = false; connectionListener.connectionLost(reason); } public boolean isConnected() { return connected; } }
package org.eclipse.birt.chart.ui.swt.wizard.data; import java.util.List; import org.eclipse.birt.chart.model.Chart; import org.eclipse.birt.chart.model.ChartWithAxes; import org.eclipse.birt.chart.model.ChartWithoutAxes; import org.eclipse.birt.chart.model.component.Series; import org.eclipse.birt.chart.model.data.DataPackage; import org.eclipse.birt.chart.model.data.Query; import org.eclipse.birt.chart.model.data.SeriesDefinition; import org.eclipse.birt.chart.model.data.SeriesGrouping; import org.eclipse.birt.chart.model.data.impl.QueryImpl; import org.eclipse.birt.chart.ui.swt.composites.GroupSortingDialog; import org.eclipse.birt.chart.ui.swt.composites.YOptionalGroupSortingDialog; import org.eclipse.birt.chart.ui.swt.wizard.ChartAdapter; import org.eclipse.birt.chart.ui.swt.wizard.ChartWizardContext; import org.eclipse.birt.chart.ui.util.ChartUIUtil; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.jface.window.Window; import org.eclipse.swt.events.ModifyEvent; /** * The component is used to set value series grouping. * * @since 2.3 */ public class YOptionalDataDefinitionComponent extends BaseDataDefinitionComponent { /** * @param queryType * @param seriesdefinition * @param query * @param context * @param title */ public YOptionalDataDefinitionComponent( String queryType, SeriesDefinition seriesdefinition, Query query, ChartWizardContext context, String title ) { super( queryType, seriesdefinition, query, context, title ); } /** * @param style * @param queryType * @param seriesdefinition * @param query * @param context * @param title */ public YOptionalDataDefinitionComponent( int style, String queryType, SeriesDefinition seriesdefinition, Query query, ChartWizardContext context, String title ) { super( style, queryType, seriesdefinition, query, context, title ); } /** * Create instance of <code>GroupSortingDialog</code> for Y * series. * * @param sdBackup * @return */ protected GroupSortingDialog createGroupSortingDialog( SeriesDefinition sdBackup ) { return new YOptionalGroupSortingDialog( cmpTop.getShell( ), context, sdBackup, false, false ); } protected void handleGroupAction( ) { SeriesDefinition sdBackup = (SeriesDefinition) EcoreUtil.copy( seriesdefinition ); GroupSortingDialog groupDialog = createGroupSortingDialog( sdBackup ); if ( groupDialog.open( ) == Window.OK ) { if ( !sdBackup.eIsSet( DataPackage.eINSTANCE.getSeriesDefinition_Sorting( ) ) ) { seriesdefinition.eUnset( DataPackage.eINSTANCE.getSeriesDefinition_Sorting( ) ); } else { seriesdefinition.setSorting( sdBackup.getSorting( ) ); } // Update the query sorting of other series. ChartAdapter.beginIgnoreNotifications( ); List<?> sds = ChartUIUtil.getAllOrthogonalSeriesDefinitions( context.getModel( ) ); for ( int i = 0; i < sds.size( ); i++ ) { if ( i != 0 ) { // Except for the first, which should be // changed manually. SeriesDefinition sdf = (SeriesDefinition) sds.get( i ); if ( !sdBackup.eIsSet( DataPackage.eINSTANCE.getSeriesDefinition_Sorting( ) ) ) { sdf.eUnset( DataPackage.eINSTANCE.getSeriesDefinition_Sorting( ) ); } else { sdf.setSorting( sdBackup.getSorting( ) ); } } } ChartAdapter.endIgnoreNotifications( ); seriesdefinition.setSortKey( sdBackup.getSortKey( ) ); seriesdefinition.getSortKey( ) .eAdapters( ) .addAll( seriesdefinition.eAdapters( ) ); if ( seriesdefinition.getQuery( ) != null ) { if ( sdBackup.getQuery( ).getGrouping( ) == null ) { // If it is cube set case, the grouping should be null. return; } seriesdefinition.getQuery( ) .setGrouping( sdBackup.getQuery( ).getGrouping( ) ); seriesdefinition.getQuery( ) .getGrouping( ) .eAdapters( ) .addAll( seriesdefinition.getQuery( ).eAdapters( ) ); // Update the query grouping of other series. ChartAdapter.beginIgnoreNotifications( ); for ( int i = 0; i < sds.size( ); i++ ) { if ( i != 0 ) { SeriesDefinition sdf = (SeriesDefinition) sds.get( i ); sdf.getQuery( ) .setGrouping( (SeriesGrouping) EcoreUtil.copy( seriesdefinition.getQuery( ) .getGrouping( ) ) ); sdf.getQuery( ) .getGrouping( ) .eAdapters( ) .addAll( sdf.getQuery( ).eAdapters( ) ); } } ChartAdapter.endIgnoreNotifications( ); ChartUIUtil.checkGroupType( context, context.getModel( ) ); } } } /* (non-Javadoc) * @see org.eclipse.birt.chart.ui.swt.wizard.data.BaseDataDefinitionComponent#saveQuery() */ protected void saveQuery() { super.saveQuery( ); updateBaseSeriesSortKey(); } /* (non-Javadoc) * @see org.eclipse.birt.chart.ui.swt.wizard.data.BaseDataDefinitionComponent#modifyText(org.eclipse.swt.events.ModifyEvent) */ public void modifyText( ModifyEvent e ) { super.modifyText( e ); if ( isQueryModified && e.getSource( ) == txtDefinition ) { updateBaseSeriesSortKey( ); } } /** * If Y grouping is set, the SortKey of base series only allow base series expression. */ private void updateBaseSeriesSortKey( ) { String yGrouping = query.getDefinition( ); if ( yGrouping != null && !"".equals( yGrouping ) ) //$NON-NLS-1$ { // If Y grouping is set and if the sort key of base series is set, // we must ensure the sort key is base series expression, don't // allow other expression. Chart cm = context.getModel( ); SeriesDefinition baseSD = null; if ( cm instanceof ChartWithAxes ) { ChartWithAxes cwa = (ChartWithAxes) cm; baseSD = (SeriesDefinition) cwa.getBaseAxes( )[0].getSeriesDefinitions( ) .get( 0 ); } else if ( cm instanceof ChartWithoutAxes ) { ChartWithoutAxes cwoa = (ChartWithoutAxes) cm; baseSD = (SeriesDefinition) cwoa.getSeriesDefinitions( ) .get( 0 ); } if ( baseSD.isSetSorting( ) ) { Series s = (Series) baseSD.getSeries( ).get( 0 ); String baseExpr = ( (Query) s.getDataDefinition( ).get( 0 ) ).getDefinition( ); if ( baseSD.getSortKey( ) == null ) { Query q = QueryImpl.create( baseExpr ); baseSD.setSortKey( q ); q.eAdapters( ).addAll( baseSD.eAdapters( ) ); } else { baseSD.getSortKey( ).setDefinition( baseExpr ); } } } } /* * (non-Javadoc) * * @see * org.eclipse.birt.chart.ui.swt.wizard.data.BaseDataDefinitionComponent * #updateQuery(java.lang.String) */ @Override public void updateQuery( String expression ) { super.updateQuery( expression ); ChartUIUtil.setAllGroupingQueryExceptFirst( context.getModel( ), expression ); } }
package com.sap.core.odata.processor.core.jpa.model; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import javax.persistence.metamodel.Attribute; import org.junit.BeforeClass; import org.junit.Test; import com.sap.core.odata.api.edm.FullQualifiedName; import com.sap.core.odata.api.edm.provider.Association; import com.sap.core.odata.api.edm.provider.AssociationEnd; import com.sap.core.odata.processor.api.jpa.access.JPAEdmBuilder; import com.sap.core.odata.processor.api.jpa.exception.ODataJPAModelException; import com.sap.core.odata.processor.api.jpa.exception.ODataJPARuntimeException; import com.sap.core.odata.processor.core.jpa.model.mock.JPAAttributeMock; public class JPAEdmNavigationPropertyTest extends JPAEdmTestModelView { private static JPAEdmNavigationProperty objNavigationProperty; private static JPAEdmNavigationPropertyTest navPropView; @BeforeClass public static void setup() { JPAEdmNavigationPropertyTest localView = new JPAEdmNavigationPropertyTest(); navPropView = new JPAEdmNavigationPropertyTest(); objNavigationProperty = new JPAEdmNavigationProperty(localView, localView); try { objNavigationProperty.getBuilder().build(); } catch (ODataJPAModelException e) { fail("ODataJPAModelException not expected"); } catch (ODataJPARuntimeException e) { fail("ODataJPARuntimeException not expected"); } } @Override public String getpUnitName() { return "salesorderprocessing"; } private Attribute<?, ?> getJPAAttributeLocal() { AttributeMock<Object, String> attr = new AttributeMock<Object, String>(); return attr; } @Override public Attribute<?, ?> getJPAAttribute() { return getJPAAttributeLocal(); } @Override public Association getEdmAssociation() { Association association = new Association(); association.setName("Assoc_SalesOrderHeader_SalesOrderItem"); association.setEnd1(new AssociationEnd().setType( new FullQualifiedName("salesorderprocessing", "String")) .setRole("SalesOrderHeader")); association.setEnd2(new AssociationEnd() .setType( new FullQualifiedName("salesorderprocessing", "SalesOrderItem")).setRole("SalesOrderItem")); return association; } @Test public void testGetBuilder() { assertNotNull(objNavigationProperty.getBuilder()); } @Test public void testGetBuilderIdempotent() { JPAEdmBuilder builder1 = objNavigationProperty.getBuilder(); JPAEdmBuilder builder2 = objNavigationProperty.getBuilder(); assertEquals(builder1.hashCode(), builder2.hashCode()); } @Test public void testGetEdmNavigationProperty() { if(objNavigationProperty == null || objNavigationProperty.getEdmNavigationProperty() == null ){ JPAEdmNavigationPropertyTest localView = new JPAEdmNavigationPropertyTest(); navPropView = new JPAEdmNavigationPropertyTest(); objNavigationProperty = new JPAEdmNavigationProperty(localView, localView); try { objNavigationProperty.getBuilder().build(); } catch (ODataJPAModelException e) { fail("ODataJPAModelException not expected"); } catch (ODataJPARuntimeException e) { fail("ODataJPARuntimeException not expected"); } } assertEquals( objNavigationProperty.getEdmNavigationProperty().getName(), "StringDetails"); } @Test public void testGetConsistentEdmNavigationProperties() { assertTrue(objNavigationProperty.getConsistentEdmNavigationProperties() .size() > 0); } @Test public void testAddJPAEdmNavigationPropertyView() { JPAEdmNavigationPropertyTest localView = new JPAEdmNavigationPropertyTest(); navPropView = new JPAEdmNavigationPropertyTest(); objNavigationProperty = new JPAEdmNavigationProperty(localView, localView); try { objNavigationProperty.getBuilder().build(); } catch (ODataJPAModelException e) { fail("ODataJPAModelException not expected"); } catch (ODataJPARuntimeException e) { fail("ODataJPARuntimeException not expected"); } objNavigationProperty.addJPAEdmNavigationPropertyView(navPropView); assertTrue(objNavigationProperty.getConsistentEdmNavigationProperties() .size() > 1); } @Override public boolean isConsistent() { return true; } @Test public void testBuildNavigationProperty() throws ODataJPAModelException { try { objNavigationProperty.getBuilder().build(); } catch (ODataJPARuntimeException e) { fail("Not expected"); } assertEquals(objNavigationProperty.getEdmNavigationProperty() .getFromRole(), "SalesOrderItem"); assertEquals(objNavigationProperty.getEdmNavigationProperty() .getToRole(), "SalesOrderHeader"); } @SuppressWarnings("hiding") private class AttributeMock<Object, String> extends JPAAttributeMock<Object, String> { @SuppressWarnings("unchecked") @Override public Class<String> getJavaType() { return (Class<String>) java.lang.String.class; } } }
package org.deeplearning4j.models.word2vec.wordstore; import lombok.Data; import lombok.NonNull; import org.deeplearning4j.models.embeddings.WeightLookupTable; import org.deeplearning4j.models.embeddings.wordvectors.WordVectors; import org.deeplearning4j.models.sequencevectors.interfaces.SequenceIterator; import org.deeplearning4j.models.sequencevectors.sequence.Sequence; import org.deeplearning4j.models.sequencevectors.sequence.SequenceElement; import org.deeplearning4j.models.word2vec.Huffman; import org.deeplearning4j.models.word2vec.wordstore.inmemory.AbstractCache; import org.deeplearning4j.text.invertedindex.InvertedIndex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicLong; /** * * This class can be used to build joint vocabulary from special sources, that should be treated separately. * I.e. words from one source should have minWordFrequency set to 1, while the rest of corpus should have minWordFrequency set to 5. * So, here's the way to deal with it. * * It also can be used to simply build vocabulary out of arbitrary number of Sequences derived from arbitrary number of SequenceIterators * * @author raver119@gmail.com */ public class VocabConstructor<T extends SequenceElement> { private List<VocabSource<T>> sources = new ArrayList<>(); private VocabCache<T> cache; private List<String> stopWords; private boolean useAdaGrad = false; private boolean fetchLabels = false; private int limit; private AtomicLong seqCount = new AtomicLong(0); private InvertedIndex<T> index; private boolean enableScavenger = false; protected static final Logger log = LoggerFactory.getLogger(VocabConstructor.class); private VocabConstructor() { } /** * Placeholder for future implementation * @return */ protected WeightLookupTable<T> buildExtendedLookupTable() { return null; } /** * Placeholder for future implementation * @return */ protected VocabCache<T> buildExtendedVocabulary() { return null; } /** * This method transfers existing WordVectors model into current one * * @param wordVectors * @return */ @SuppressWarnings("unchecked") // method is safe, since all calls inside are using generic SequenceElement methods public VocabCache<T> buildMergedVocabulary(@NonNull WordVectors wordVectors, boolean fetchLabels) { return buildMergedVocabulary((VocabCache<T>) wordVectors.vocab(), fetchLabels); } /** * This method returns total number of sequences passed through VocabConstructor * * @return */ public long getNumberOfSequences() { return seqCount.get(); } /** * This method transfers existing vocabulary into current one * * Please note: this method expects source vocabulary has Huffman tree indexes applied * * @param vocabCache * @return */ public VocabCache<T> buildMergedVocabulary(@NonNull VocabCache<T> vocabCache, boolean fetchLabels) { if (cache == null) cache = new AbstractCache.Builder<T>().build(); for (int t = 0; t < vocabCache.numWords(); t++) { String label = vocabCache.wordAtIndex(t); if (label == null) continue; T element = vocabCache.wordFor(label); // skip this element if it's a label, and user don't want labels to be merged if (!fetchLabels && element.isLabel()) continue; //element.setIndex(t); cache.addToken(element); cache.addWordToIndex(element.getIndex(), element.getLabel()); // backward compatibility code cache.putVocabWord(element.getLabel()); } if (cache.numWords() == 0) throw new IllegalStateException("Source VocabCache has no indexes available, transfer is impossible"); /* Now, when we have transferred vocab, we should roll over iterator, and gather labels, if any */ log.info("Vocab size before labels: " + cache.numWords()); if (fetchLabels) { for(VocabSource<T> source: sources) { SequenceIterator<T> iterator = source.getIterator(); iterator.reset(); while (iterator.hasMoreSequences()) { Sequence<T> sequence = iterator.nextSequence(); seqCount.incrementAndGet(); if (sequence.getSequenceLabels() != null) for (T label: sequence.getSequenceLabels()) { if (!cache.containsWord(label.getLabel())) { label.markAsLabel(true); label.setSpecial(true); label.setIndex(cache.numWords()); cache.addToken(label); cache.addWordToIndex(label.getIndex(), label.getLabel()); // backward compatibility code cache.putVocabWord(label.getLabel()); // log.info("Adding label ["+label.getLabel()+"]: " + cache.wordFor(label.getLabel())); } // else log.info("Label ["+label.getLabel()+"] already exists: " + cache.wordFor(label.getLabel())); } } } } log.info("Vocab size after labels: " + cache.numWords()); return cache; } /** * This method scans all sources passed through builder, and returns all words as vocab. * If TargetVocabCache was set during instance creation, it'll be filled too. * * * @return */ public VocabCache<T> buildJointVocabulary(boolean resetCounters, boolean buildHuffmanTree) { long lastTime = System.currentTimeMillis(); long lastSequences = 0; long lastElements = 0; long startTime = lastTime; long startWords = 0; AtomicLong parsedCount = new AtomicLong(0); if (resetCounters && buildHuffmanTree) throw new IllegalStateException("You can't reset counters and build Huffman tree at the same time!"); if (cache == null) cache = new AbstractCache.Builder<T>().build(); log.debug("Target vocab size before building: [" + cache.numWords() + "]"); final AtomicLong loopCounter = new AtomicLong(0); AbstractCache<T> topHolder = new AbstractCache.Builder<T>() .minElementFrequency(0) .build(); int cnt = 0; for(VocabSource<T> source: sources) { SequenceIterator<T> iterator = source.getIterator(); iterator.reset(); log.debug("Trying source iterator: ["+ cnt+"]"); log.debug("Target vocab size before building: [" + cache.numWords() + "]"); cnt++; AbstractCache<T> tempHolder = new AbstractCache.Builder<T>().build(); int numProc = Runtime.getRuntime().availableProcessors(); int numThreads = Math.max(numProc / 2, 2); ExecutorService executorService = new ThreadPoolExecutor(numThreads, numThreads, 0L, TimeUnit.MILLISECONDS, new LinkedTransferQueue<Runnable>());//Executors.newFixedThreadPool(Math.max(numProc / 2, 2)); final AtomicLong execCounter = new AtomicLong(0); final AtomicLong finCounter = new AtomicLong(0); int sequences = 0; while (iterator.hasMoreSequences()) { long time1 = System.currentTimeMillis(); Sequence<T> document = iterator.nextSequence(); long time2 = System.currentTimeMillis(); seqCount.incrementAndGet(); parsedCount.addAndGet(document.size()); tempHolder.incrementTotalDocCount(); execCounter.incrementAndGet(); VocabRunnable runnable = new VocabRunnable(tempHolder, document, finCounter, loopCounter); /* executorService.submit(runnable); // as we see in profiler, this lock isn't really happen too often // we don't want too much left in tail while (execCounter.get() - finCounter.get() > numProc) { try { Thread.sleep(2); } catch (Exception e) { } } */ sequences++; if (seqCount.get() % 100000 == 0) { long currentTime = System.currentTimeMillis(); long currentSequences = seqCount.get(); long currentElements = parsedCount.get(); double seconds = (currentTime - lastTime) / (double) 1000; double seqPerSec = (currentSequences - lastSequences) / seconds; double elPerSec = (currentElements - lastElements) / seconds; log.info("Document time: {} ms", time2 - time1); log.info("Sequences checked: [{}]; Current vocabulary size: [{}]; Sequences/sec: {}; Words/sec: {};", seqCount.get(), tempHolder.numWords(), String.format("%.2f", seqPerSec), String.format("%.2f", elPerSec)); lastTime = currentTime; lastElements = currentElements; lastSequences = currentSequences; } /** * Firing scavenger loop */ if (enableScavenger && loopCounter.get() >= 2000000 && tempHolder.numWords() > 10000000) { log.info("Starting scavenger..."); while (execCounter.get() != finCounter.get()) { try { Thread.sleep(2); } catch (Exception e) { } } filterVocab(tempHolder, Math.max(1, source.getMinWordFrequency() / 2)); loopCounter.set(0); } } // block untill all threads are finished log.info("Wating till all processes stop..."); while (execCounter.get() != finCounter.get()) { try { Thread.sleep(2); } catch (Exception e) { } } // apply minWordFrequency set for this source log.debug("Vocab size before truncation: [" + tempHolder.numWords() + "], NumWords: [" + tempHolder.totalWordOccurrences()+ "], sequences parsed: [" + seqCount.get()+ "], counter: ["+parsedCount.get()+"]"); if (source.getMinWordFrequency() > 0) { filterVocab(tempHolder, source.getMinWordFrequency()); } log.debug("Vocab size after truncation: [" + tempHolder.numWords() + "], NumWords: [" + tempHolder.totalWordOccurrences()+ "], sequences parsed: [" + seqCount.get()+ "], counter: ["+parsedCount.get()+"]"); // at this moment we're ready to transfer topHolder.importVocabulary(tempHolder); } // at this moment, we have vocabulary full of words, and we have to reset counters before transfer everything back to VocabCache //topHolder.resetWordCounters(); cache.importVocabulary(topHolder); if (resetCounters) { for (T element: cache.vocabWords()) { element.setElementFrequency(0); } cache.updateWordsOccurencies(); } if (buildHuffmanTree) { Huffman huffman = new Huffman(cache.vocabWords()); huffman.build(); huffman.applyIndexes(cache); //topHolder.updateHuffmanCodes(); if (limit > 0) { LinkedBlockingQueue<String> labelsToRemove = new LinkedBlockingQueue<>(); for (T element : cache.vocabWords()) { if (element.getIndex() > limit && !element.isSpecial() && !element.isLabel()) labelsToRemove.add(element.getLabel()); } for (String label: labelsToRemove) { cache.removeElement(label); } } } long endSequences = seqCount.get(); long endTime = System.currentTimeMillis(); double seconds = (endTime - startTime) / (double) 1000; double seqPerSec = endSequences / seconds; log.info("Sequences checked: [{}], Current vocabulary size: [{}]; Sequences/sec: [{}];", seqCount.get(), cache.numWords(), String.format("%.2f", seqPerSec)); return cache; } protected void filterVocab(AbstractCache<T> cache, int minWordFrequency) { int numWords = cache.numWords(); LinkedBlockingQueue<String> labelsToRemove = new LinkedBlockingQueue<>(); for (T element : cache.vocabWords()) { if (element.getElementFrequency() < minWordFrequency && !element.isSpecial() && !element.isLabel()) labelsToRemove.add(element.getLabel()); } for (String label: labelsToRemove) { cache.removeElement(label); } log.debug("Scavenger: Words before: {}; Words after: {};", numWords, cache.numWords()); } public static class Builder<T extends SequenceElement> { private List<VocabSource<T>> sources = new ArrayList<>(); private VocabCache<T> cache; private List<String> stopWords = new ArrayList<>(); private boolean useAdaGrad = false; private boolean fetchLabels = false; private InvertedIndex<T> index; private int limit; private boolean enableScavenger = false; public Builder() { } /** * This method sets the limit to resulting vocabulary size. * * PLEASE NOTE: This method is applicable only if huffman tree is built. * * @param limit * @return */ public Builder<T> setEntriesLimit(int limit) { this.limit = limit; return this; } /** * Defines, if adaptive gradients should be created during vocabulary mastering * * @param useAdaGrad * @return */ protected Builder<T> useAdaGrad(boolean useAdaGrad) { this.useAdaGrad = useAdaGrad; return this; } /** * After temporary internal vocabulary is built, it will be transferred to target VocabCache you pass here * * @param cache target VocabCache * @return */ public Builder<T> setTargetVocabCache(@NonNull VocabCache<T> cache) { this.cache = cache; return this; } /** * Adds SequenceIterator for vocabulary construction. * Please note, you can add as many sources, as you wish. * * @param iterator SequenceIterator to build vocabulary from * @param minElementFrequency elements with frequency below this value will be removed from vocabulary * @return */ public Builder<T> addSource(@NonNull SequenceIterator<T> iterator, int minElementFrequency) { sources.add(new VocabSource<T>(iterator, minElementFrequency)); return this; } /* public Builder<T> addSource(LabelAwareIterator iterator, int minWordFrequency) { sources.add(new VocabSource(iterator, minWordFrequency)); return this; } public Builder<T> addSource(SentenceIterator iterator, int minWordFrequency) { sources.add(new VocabSource(new SentenceIteratorConverter(iterator), minWordFrequency)); return this; } */ /* public Builder setTokenizerFactory(@NonNull TokenizerFactory factory) { this.tokenizerFactory = factory; return this; } */ public Builder<T> setStopWords(@NonNull List<String> stopWords) { this.stopWords = stopWords; return this; } /** * Sets, if labels should be fetched, during vocab building * * @param reallyFetch * @return */ public Builder<T> fetchLabels(boolean reallyFetch) { this.fetchLabels = reallyFetch; return this; } public Builder<T> setIndex(InvertedIndex<T> index) { this.index = index; return this; } public Builder<T> enableScavenger(boolean reallyEnable) { this.enableScavenger = reallyEnable; return this; } public VocabConstructor<T> build() { VocabConstructor<T> constructor = new VocabConstructor<>(); constructor.sources = this.sources; constructor.cache = this.cache; constructor.stopWords = this.stopWords; constructor.useAdaGrad = this.useAdaGrad; constructor.fetchLabels = this.fetchLabels; constructor.limit = this.limit; constructor.index = this.index; constructor.enableScavenger = this.enableScavenger; return constructor; } } @Data private static class VocabSource<T extends SequenceElement> { @NonNull private SequenceIterator<T> iterator; @NonNull private int minWordFrequency; } protected class VocabRunnable implements Runnable { private final AtomicLong finalCounter; private final Sequence<T> document; private final AbstractCache<T> targetVocab; private final AtomicLong loopCounter; public VocabRunnable(@NonNull AbstractCache<T> targetVocab, @NonNull Sequence<T> sequence, @NonNull AtomicLong finalCounter, @NonNull AtomicLong loopCounter) { this.finalCounter = finalCounter; this.document = sequence; this.targetVocab = targetVocab; this.loopCounter = loopCounter; } @Override public void run() { Map<String, AtomicLong> seqMap = new HashMap<>(); // log.info("Sequence length: ["+ document.getElements().size()+"]"); if (fetchLabels) { T labelWord = document.getSequenceLabel(); labelWord.setSpecial(true); labelWord.markAsLabel(true); labelWord.setElementFrequency(1); targetVocab.addToken(labelWord); } List<String> tokens = document.asLabels(); for (String token: tokens) { if (stopWords !=null && stopWords.contains(token)) continue; if (token == null || token.isEmpty()) continue; if (!targetVocab.containsWord(token)) { T element = document.getElementByLabel(token); element.setElementFrequency(1); //targetVocab.addToken(element); // elementsCounter.incrementAndGet(); loopCounter.incrementAndGet(); // if there's no such element in tempHolder, it's safe to set seqCount to 1 element.setSequencesCount(1); seqMap.put(token, new AtomicLong(0)); } else { targetVocab.incrementWordCount(token); // if element exists in tempHolder, we should update it seqCount, but only once per sequence if (!seqMap.containsKey(token)) { seqMap.put(token, new AtomicLong(1)); T element = targetVocab.wordFor(token); element.incrementSequencesCount(); } if (index != null) { if (document.getSequenceLabel() != null) { index.addWordsToDoc(index.numDocuments(), document.getElements(), document.getSequenceLabel()); } else { index.addWordsToDoc(index.numDocuments(),document.getElements()); } } } } finalCounter.incrementAndGet(); } } }
package edu.uci.ics.hivesterix.runtime.provider; import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException; import edu.uci.ics.hyracks.algebricks.data.IBinaryHashFunctionFamilyProvider; import edu.uci.ics.hyracks.api.dataflow.value.IBinaryHashFunctionFamily; import edu.uci.ics.hyracks.data.std.accessors.MurmurHash3BinaryHashFunctionFamily; public class HiveBinaryHashFunctionFamilyProvider implements IBinaryHashFunctionFamilyProvider { public static HiveBinaryHashFunctionFamilyProvider INSTANCE = new HiveBinaryHashFunctionFamilyProvider(); private HiveBinaryHashFunctionFamilyProvider() { } @Override public IBinaryHashFunctionFamily getBinaryHashFunctionFamily(Object type) throws AlgebricksException { return MurmurHash3BinaryHashFunctionFamily.INSTANCE; } }
package org.jtalks.jcommune.web.controller; import org.jtalks.jcommune.model.entity.PrivateMessage; import org.jtalks.jcommune.service.PrivateMessageService; import org.jtalks.jcommune.service.exceptions.NotFoundException; import org.jtalks.jcommune.web.dto.PrivateMessageDto; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid; /** * MVC controller for Private Messaging. Handles request for inbox, outbox and new private messages. * * @author Pavel Vervenko * @author Max Malakhov * @author Kirill Afonin */ @Controller public class PrivateMessageController { private final PrivateMessageService pmService; private final Logger logger = LoggerFactory.getLogger(getClass()); /** * Requires {@link PrivateMessageService} for manipulations with messages. * * @param pmService the PrivateMessageService instance */ @Autowired public PrivateMessageController(PrivateMessageService pmService) { this.pmService = pmService; } /** * Render the PM inbox page with the list of incoming messages for the /inbox URI. * * @return {@code ModelAndView} with added list of inbox messages */ @RequestMapping(value = "/pm/inbox", method = RequestMethod.GET) public ModelAndView displayInboxPage() { return new ModelAndView("pm/inbox", "pmList", pmService.getInboxForCurrentUser()); } /** * Render the PM outbox page with the list of sent messages for the /outbox URI. * * @return {@code ModelAndView} with added list of outbox messages */ @RequestMapping(value = "/pm/outbox", method = RequestMethod.GET) public ModelAndView displayOutboxPage() { return new ModelAndView("pm/outbox", "pmList", pmService.getOutboxForCurrentUser()); } /** * Render the page with a form for creation new Private Message with empty binded {@link PrivateMessageDto}. * * @return {@code ModelAndView} with the form */ @RequestMapping(value = "/pm/new", method = RequestMethod.GET) public ModelAndView displayNewPMPage() { return new ModelAndView("pm/pmForm", "privateMessageDto", new PrivateMessageDto()); } /** * Save the PrivateMessage for the filled in PrivateMessageDto. * * @param pmDto {@link PrivateMessageDto} populated in form * @param result result of {@link PrivateMessageDto} validation * @return redirect to /inbox on success or back to "/new_pm" on validation errors */ @RequestMapping(value = "/pm/new", method = RequestMethod.POST) public String send(@Valid @ModelAttribute PrivateMessageDto pmDto, BindingResult result) { if (result.hasErrors()) { return "pm/pmForm"; } try { pmService.sendMessage(pmDto.getTitle(), pmDto.getBody(), pmDto.getRecipient()); } catch (NotFoundException nfe) { logger.info("User not found: {} ", pmDto.getRecipient()); result.rejectValue("recipient", "label.wrong_recipient"); return "pm/pmForm"; } return "redirect:/pm/outbox.html"; } /** * Show page with private message details. * * @param folder message folder (inbox/outbox/drafts) * @param pmId {@link PrivateMessage} id * @return {@code ModelAndView} with a message * @throws org.jtalks.jcommune.service.exceptions.NotFoundException * when message not found */ @RequestMapping(value = "/pm/{folder}/{pmId}", method = RequestMethod.GET) public ModelAndView show(@PathVariable("folder") String folder, @PathVariable("pmId") Long pmId) throws NotFoundException { PrivateMessage pm = pmService.get(pmId); if ("inbox".equals(folder)) { pmService.markAsReaded(pm); } return new ModelAndView("pm/showPm", "pm", pm); } /** * Get list of current user's list of draft messages. * * @return {@code ModelAndView} with list of messages */ @RequestMapping(value = "/pm/drafts", method = RequestMethod.GET) public ModelAndView displayDraftsPage() { return new ModelAndView("pm/drafts", "pmList", pmService.getDraftsFromCurrentUser()); } /** * @param pmId {@link PrivateMessage} id * @return private messsage form view and populated form dto * @throws NotFoundException when message not found */ @RequestMapping(value = "/pm/{pmId}/edit", method = RequestMethod.GET) public ModelAndView edit(@PathVariable("pmId") Long pmId) throws NotFoundException { PrivateMessage pm = pmService.get(pmId); return new ModelAndView("pm/pmForm", "privateMessageDto", PrivateMessageDto.getDtoFor(pm)); } /** * Save private message as draft. * * @param pmDto Dto populated in form * @param result validation result * @return redirect to "drafts" folder if saved successfully or show form with error message */ @RequestMapping(value = "/pm/save", method = RequestMethod.POST) public String save(@Valid @ModelAttribute PrivateMessageDto pmDto, BindingResult result) { if (result.hasErrors()) { return "pm/pmForm"; } try { pmService.saveDraft(pmDto.getId(), pmDto.getTitle(), pmDto.getBody(), pmDto.getRecipient()); } catch (NotFoundException nfe) { logger.info("User not found: {} ", pmDto.getRecipient()); result.rejectValue("recipient", "label.wrong_recipient"); return "pm/pmForm"; } return "redirect:/pm/drafts.html"; } }
package org.opendaylight.controller.md.sal.dom.store.impl.tree; import static com.google.common.base.Preconditions.checkState; import java.util.LinkedHashMap; import java.util.Map; import javax.annotation.concurrent.GuardedBy; import org.opendaylight.yangtools.concepts.Identifiable; import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.primitives.UnsignedLong; /** * Node Modification Node and Tree * * Tree which structurally resembles data tree and captures client modifications * to the data store tree. * * This tree is lazily created and populated via {@link #modifyChild(PathArgument)} * and {@link StoreMetadataNode} which represents original state {@link #getOriginal()}. * */ public class NodeModification implements StoreTreeNode<NodeModification>, Identifiable<PathArgument> { public static final Predicate<NodeModification> IS_TERMINAL_PREDICATE = new Predicate<NodeModification>() { @Override public boolean apply(final NodeModification input) { return input.getModificationType() == ModificationType.WRITE || input.getModificationType() == ModificationType.DELETE; } }; private final PathArgument identifier; private ModificationType modificationType = ModificationType.UNMODIFIED; private final Optional<StoreMetadataNode> original; private NormalizedNode<?, ?> value; private UnsignedLong subtreeVersion; private Optional<StoreMetadataNode> snapshotCache; private final Map<PathArgument, NodeModification> childModification; @GuardedBy("this") private boolean sealed = false; protected NodeModification(final PathArgument identifier, final Optional<StoreMetadataNode> original) { this.identifier = identifier; this.original = original; childModification = new LinkedHashMap<>(); } /** * * * @return */ public NormalizedNode<?, ?> getWritenValue() { return value; } @Override public PathArgument getIdentifier() { return identifier; } /** * * Returns original store metadata * @return original store metadata */ public final Optional<StoreMetadataNode> getOriginal() { return original; } /** * Returns modification type * * @return modification type */ public final ModificationType getModificationType() { return modificationType; } /** * * Returns child modification if child was modified * * @return Child modification if direct child or it's subtree * was modified. * */ @Override public Optional<NodeModification> getChild(final PathArgument child) { return Optional.<NodeModification> fromNullable(childModification.get(child)); } /** * * Returns child modification if child was modified, creates {@link NodeModification} * for child otherwise. * * If this node's {@link ModificationType} is {@link ModificationType#UNMODIFIED} * changes modification type to {@link ModificationType#SUBTREE_MODIFIED} * * @param child * @return {@link NodeModification} for specified child, with {@link #getOriginal()} * containing child metadata if child was present in original data. */ public synchronized NodeModification modifyChild(final PathArgument child) { checkSealed(); clearSnapshot(); if(modificationType == ModificationType.UNMODIFIED) { updateModificationType(ModificationType.SUBTREE_MODIFIED); } final NodeModification potential = childModification.get(child); if (potential != null) { return potential; } Optional<StoreMetadataNode> currentMetadata = Optional.absent(); if(original.isPresent()) { currentMetadata = original.get().getChild(child); } NodeModification newlyCreated = new NodeModification(child,currentMetadata); childModification.put(child, newlyCreated); return newlyCreated; } /** * * Returns all recorded direct child modification * * @return all recorded direct child modifications */ public Iterable<NodeModification> getModifications() { return childModification.values(); } /** * * Records a delete for associated node. * */ public synchronized void delete() { checkSealed(); clearSnapshot(); updateModificationType(ModificationType.DELETE); childModification.clear(); this.value = null; } /** * * Records a write for associated node. * * @param value */ public synchronized void write(final NormalizedNode<?, ?> value) { checkSealed(); clearSnapshot(); updateModificationType(ModificationType.WRITE); childModification.clear(); this.value = value; } @GuardedBy("this") private void checkSealed() { checkState(!sealed, "Node Modification is sealed. No further changes allowed."); } public synchronized void seal() { sealed = true; clearSnapshot(); for(NodeModification child : childModification.values()) { child.seal(); } } private void clearSnapshot() { snapshotCache = null; } public Optional<StoreMetadataNode> storeSnapshot(final Optional<StoreMetadataNode> snapshot) { snapshotCache = snapshot; return snapshot; } public Optional<Optional<StoreMetadataNode>> getSnapshotCache() { return Optional.fromNullable(snapshotCache); } public boolean hasAdditionalModifications() { return !childModification.isEmpty(); } @GuardedBy("this") private void updateModificationType(final ModificationType type) { modificationType = type; clearSnapshot(); } @Override public String toString() { return "NodeModification [identifier=" + identifier + ", modificationType=" + modificationType + ", childModification=" + childModification + "]"; } public static NodeModification createUnmodified(final StoreMetadataNode metadataTree) { return new NodeModification(metadataTree.getIdentifier(), Optional.of(metadataTree)); } }
package org.opendaylight.controller.switchmanager.internal; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Collections; import java.util.Dictionary; import java.util.EnumSet; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.felix.dm.Component; import org.eclipse.osgi.framework.console.CommandInterpreter; import org.eclipse.osgi.framework.console.CommandProvider; import org.opendaylight.controller.clustering.services.CacheConfigException; import org.opendaylight.controller.clustering.services.CacheExistException; import org.opendaylight.controller.clustering.services.IClusterContainerServices; import org.opendaylight.controller.clustering.services.IClusterServices; import org.opendaylight.controller.configuration.ConfigurationObject; import org.opendaylight.controller.configuration.IConfigurationContainerAware; import org.opendaylight.controller.configuration.IConfigurationContainerService; import org.opendaylight.controller.sal.core.Bandwidth; import org.opendaylight.controller.sal.core.Config; import org.opendaylight.controller.sal.core.ConstructionException; import org.opendaylight.controller.sal.core.Description; import org.opendaylight.controller.sal.core.ForwardingMode; import org.opendaylight.controller.sal.core.MacAddress; import org.opendaylight.controller.sal.core.Name; import org.opendaylight.controller.sal.core.Node; import org.opendaylight.controller.sal.core.NodeConnector; import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType; import org.opendaylight.controller.sal.core.Property; import org.opendaylight.controller.sal.core.State; import org.opendaylight.controller.sal.core.Tier; import org.opendaylight.controller.sal.core.UpdateType; import org.opendaylight.controller.sal.inventory.IInventoryService; import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates; import org.opendaylight.controller.sal.reader.NodeDescription; import org.opendaylight.controller.sal.utils.GlobalConstants; import org.opendaylight.controller.sal.utils.HexEncode; import org.opendaylight.controller.sal.utils.IObjectReader; import org.opendaylight.controller.sal.utils.Status; import org.opendaylight.controller.sal.utils.StatusCode; import org.opendaylight.controller.statisticsmanager.IStatisticsManager; import org.opendaylight.controller.switchmanager.IInventoryListener; import org.opendaylight.controller.switchmanager.ISpanAware; import org.opendaylight.controller.switchmanager.ISwitchManager; import org.opendaylight.controller.switchmanager.ISwitchManagerAware; import org.opendaylight.controller.switchmanager.SpanConfig; import org.opendaylight.controller.switchmanager.Subnet; import org.opendaylight.controller.switchmanager.SubnetConfig; import org.opendaylight.controller.switchmanager.Switch; import org.opendaylight.controller.switchmanager.SwitchConfig; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The class describes SwitchManager which is the central repository of all the * inventory data including nodes, node connectors, properties attached, Layer3 * configurations, Span configurations, node configurations, network device * representations viewed by Controller Web applications. One SwitchManager * instance per container of the network. All the node/nodeConnector properties * are maintained in the default container only. */ public class SwitchManager implements ISwitchManager, IConfigurationContainerAware, IObjectReader, IListenInventoryUpdates, CommandProvider { private static Logger log = LoggerFactory.getLogger(SwitchManager.class); private static final String SUBNETS_FILE_NAME = "subnets.conf"; private static final String SPAN_FILE_NAME = "spanPorts.conf"; private static final String SWITCH_CONFIG_FILE_NAME = "switchConfig.conf"; private final List<NodeConnector> spanNodeConnectors = new CopyOnWriteArrayList<NodeConnector>(); // Collection of Subnets keyed by the InetAddress private ConcurrentMap<InetAddress, Subnet> subnets; private ConcurrentMap<String, SubnetConfig> subnetsConfigList; private ConcurrentMap<SpanConfig, SpanConfig> spanConfigList; // manually configured parameters for the node such as name, tier, mode private ConcurrentMap<String, SwitchConfig> nodeConfigList; private ConcurrentMap<Node, Map<String, Property>> nodeProps; private ConcurrentMap<NodeConnector, Map<String, Property>> nodeConnectorProps; private ConcurrentMap<Node, Map<String, NodeConnector>> nodeConnectorNames; private ConcurrentMap<String, Property> controllerProps; private IInventoryService inventoryService; private IStatisticsManager statisticsManager; private IConfigurationContainerService configurationService; private final Set<ISwitchManagerAware> switchManagerAware = Collections .synchronizedSet(new HashSet<ISwitchManagerAware>()); private final Set<IInventoryListener> inventoryListeners = Collections .synchronizedSet(new HashSet<IInventoryListener>()); private final Set<ISpanAware> spanAware = Collections.synchronizedSet(new HashSet<ISpanAware>()); private IClusterContainerServices clusterContainerService = null; private String containerName = null; private boolean isDefaultContainer = true; private static final int REPLACE_RETRY = 1; /* Information about the default subnet. If there have been no configured subnets, i.e., * subnets.size() == 0 or subnetsConfigList.size() == 0, then this subnet will be the * only subnet returned. As soon as a user-configured subnet is created this one will * vanish. */ protected static final SubnetConfig DEFAULT_SUBNETCONFIG; protected static final Subnet DEFAULT_SUBNET; protected static final String DEFAULT_SUBNET_NAME = "default (cannot be modifed)"; static{ DEFAULT_SUBNETCONFIG = new SubnetConfig(DEFAULT_SUBNET_NAME, "0.0.0.0/0", new ArrayList<String>()); DEFAULT_SUBNET = new Subnet(DEFAULT_SUBNETCONFIG); } public void notifySubnetChange(Subnet sub, boolean add) { synchronized (switchManagerAware) { for (Object subAware : switchManagerAware) { try { ((ISwitchManagerAware) subAware).subnetNotify(sub, add); } catch (Exception e) { log.error("Failed to notify Subnet change {}", e.getMessage()); } } } } public void notifySpanPortChange(Node node, List<NodeConnector> ports, boolean add) { synchronized (spanAware) { for (Object sa : spanAware) { try { ((ISpanAware) sa).spanUpdate(node, ports, add); } catch (Exception e) { log.error("Failed to notify Span Interface change {}", e.getMessage()); } } } } private void notifyModeChange(Node node, boolean proactive) { synchronized (switchManagerAware) { for (ISwitchManagerAware service : switchManagerAware) { try { service.modeChangeNotify(node, proactive); } catch (Exception e) { log.error("Failed to notify Subnet change {}", e.getMessage()); } } } } public void startUp() { // Instantiate cluster synced variables allocateCaches(); retrieveCaches(); // Add controller MAC, if first node in the cluster if (!controllerProps.containsKey(MacAddress.name)) { byte controllerMac[] = getHardwareMAC(); if (controllerMac != null) { Property existing = controllerProps.putIfAbsent(MacAddress.name, new MacAddress(controllerMac)); if (existing == null && log.isTraceEnabled()) { log.trace("Container {}: Setting controller MAC address in the cluster: {}", getContainerName(), HexEncode.bytesToHexStringFormat(controllerMac)); } } } } public void shutDown() { } private void allocateCaches() { if (this.clusterContainerService == null) { this.nonClusterObjectCreate(); log.warn("un-initialized clusterContainerService, can't create cache"); return; } try { clusterContainerService.createCache( "switchmanager.subnetsConfigList", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache("switchmanager.spanConfigList", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache("switchmanager.nodeConfigList", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache("switchmanager.subnets", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache("switchmanager.nodeProps", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache( "switchmanager.nodeConnectorProps", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache( "switchmanager.nodeConnectorNames", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache( "switchmanager.controllerProps", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); } catch (CacheConfigException cce) { log.error("\nCache configuration invalid - check cache mode"); } catch (CacheExistException ce) { log.error("\nCache already exits - destroy and recreate if needed"); } } @SuppressWarnings({ "unchecked" }) private void retrieveCaches() { if (this.clusterContainerService == null) { log.warn("un-initialized clusterContainerService, can't create cache"); return; } subnetsConfigList = (ConcurrentMap<String, SubnetConfig>) clusterContainerService .getCache("switchmanager.subnetsConfigList"); if (subnetsConfigList == null) { log.error("\nFailed to get cache for subnetsConfigList"); } spanConfigList = (ConcurrentMap<SpanConfig, SpanConfig>) clusterContainerService .getCache("switchmanager.spanConfigList"); if (spanConfigList == null) { log.error("\nFailed to get cache for spanConfigList"); } nodeConfigList = (ConcurrentMap<String, SwitchConfig>) clusterContainerService .getCache("switchmanager.nodeConfigList"); if (nodeConfigList == null) { log.error("\nFailed to get cache for nodeConfigList"); } subnets = (ConcurrentMap<InetAddress, Subnet>) clusterContainerService .getCache("switchmanager.subnets"); if (subnets == null) { log.error("\nFailed to get cache for subnets"); } nodeProps = (ConcurrentMap<Node, Map<String, Property>>) clusterContainerService .getCache("switchmanager.nodeProps"); if (nodeProps == null) { log.error("\nFailed to get cache for nodeProps"); } nodeConnectorProps = (ConcurrentMap<NodeConnector, Map<String, Property>>) clusterContainerService .getCache("switchmanager.nodeConnectorProps"); if (nodeConnectorProps == null) { log.error("\nFailed to get cache for nodeConnectorProps"); } nodeConnectorNames = (ConcurrentMap<Node, Map<String, NodeConnector>>) clusterContainerService .getCache("switchmanager.nodeConnectorNames"); if (nodeConnectorNames == null) { log.error("\nFailed to get cache for nodeConnectorNames"); } controllerProps = (ConcurrentMap<String, Property>) clusterContainerService .getCache("switchmanager.controllerProps"); if (controllerProps == null) { log.error("\nFailed to get cache for controllerProps"); } } private void nonClusterObjectCreate() { subnetsConfigList = new ConcurrentHashMap<String, SubnetConfig>(); spanConfigList = new ConcurrentHashMap<SpanConfig, SpanConfig>(); nodeConfigList = new ConcurrentHashMap<String, SwitchConfig>(); subnets = new ConcurrentHashMap<InetAddress, Subnet>(); nodeProps = new ConcurrentHashMap<Node, Map<String, Property>>(); nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Map<String, Property>>(); nodeConnectorNames = new ConcurrentHashMap<Node, Map<String, NodeConnector>>(); controllerProps = new ConcurrentHashMap<String, Property>(); } @Override public List<SubnetConfig> getSubnetsConfigList() { // if there are no subnets, return the default subnet if(subnetsConfigList.size() == 0){ return Collections.singletonList(DEFAULT_SUBNETCONFIG); }else{ return new ArrayList<SubnetConfig>(subnetsConfigList.values()); } } @Override public SubnetConfig getSubnetConfig(String subnet) { // if there are no subnets, return the default subnet if(subnetsConfigList.isEmpty() && subnet.equalsIgnoreCase(DEFAULT_SUBNET_NAME)){ return DEFAULT_SUBNETCONFIG; }else{ return subnetsConfigList.get(subnet); } } private List<SpanConfig> getSpanConfigList(Node node) { List<SpanConfig> confList = new ArrayList<SpanConfig>(); String nodeId = node.toString(); for (SpanConfig conf : spanConfigList.values()) { if (conf.matchNode(nodeId)) { confList.add(conf); } } return confList; } public List<SwitchConfig> getNodeConfigList() { return new ArrayList<SwitchConfig>(nodeConfigList.values()); } @Override public SwitchConfig getSwitchConfig(String switchId) { return nodeConfigList.get(switchId); } public Switch getSwitchByNode(Node node) { Switch sw = new Switch(node); sw.setNode(node); MacAddress mac = (MacAddress) this.getNodeProp(node, MacAddress.name); if (mac != null) { sw.setDataLayerAddress(mac.getMacAddress()); } Set<NodeConnector> ncSet = getPhysicalNodeConnectors(node); sw.setNodeConnectors(ncSet); List<NodeConnector> ncList = new ArrayList<NodeConnector>(); for (NodeConnector nodeConnector : ncSet) { if (spanNodeConnectors.contains(nodeConnector)) { ncList.add(nodeConnector); } } sw.addSpanPorts(ncList); return sw; } @Override public List<Switch> getNetworkDevices() { List<Switch> swList = new ArrayList<Switch>(); for (Node node : getNodes()) { swList.add(getSwitchByNode(node)); } return swList; } private Status updateConfig(SubnetConfig conf, boolean add) { if (add) { if(subnetsConfigList.putIfAbsent(conf.getName(), conf) != null) { String msg = "Cluster conflict: Subnet with name " + conf.getName() + "already exists."; return new Status(StatusCode.CONFLICT, msg); } } else { subnetsConfigList.remove(conf.getName()); } return new Status(StatusCode.SUCCESS); } private Status updateDatabase(SubnetConfig conf, boolean add) { if (add) { Subnet subnetCurr = subnets.get(conf.getIPAddress()); Subnet subnet; if (subnetCurr == null) { subnet = new Subnet(conf); } else { subnet = subnetCurr.clone(); } // In case of API3 call we may receive the ports along with the // subnet creation if (!conf.isGlobal()) { subnet.addNodeConnectors(conf.getNodeConnectors()); } boolean putNewSubnet = false; if(subnetCurr == null) { if(subnets.putIfAbsent(conf.getIPAddress(), subnet) == null) { putNewSubnet = true; } } else { putNewSubnet = subnets.replace(conf.getIPAddress(), subnetCurr, subnet); } if(!putNewSubnet) { String msg = "Cluster conflict: Conflict while adding the subnet " + conf.getIPAddress(); return new Status(StatusCode.CONFLICT, msg); } // Subnet removal case } else { subnets.remove(conf.getIPAddress()); } return new Status(StatusCode.SUCCESS); } private Status semanticCheck(SubnetConfig conf) { Set<InetAddress> IPs = subnets.keySet(); if (IPs == null) { return new Status(StatusCode.SUCCESS); } Subnet newSubnet = new Subnet(conf); for (InetAddress i : IPs) { Subnet existingSubnet = subnets.get(i); if ((existingSubnet != null) && !existingSubnet.isMutualExclusive(newSubnet)) { return new Status(StatusCode.CONFLICT, "This subnet conflicts with an existing one."); } } return new Status(StatusCode.SUCCESS); } private Status addRemoveSubnet(SubnetConfig conf, boolean isAdding) { // Valid configuration check Status status = conf.validate(); if (!status.isSuccess()) { log.warn(status.getDescription()); return status; } if (isAdding) { // Presence check if (subnetsConfigList.containsKey(conf.getName())) { return new Status(StatusCode.CONFLICT, "Subnet with the specified name already exists."); } // Semantic check status = semanticCheck(conf); if (!status.isSuccess()) { return status; } } else { if (conf.getName().equalsIgnoreCase(DEFAULT_SUBNET_NAME)) { return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed"); } } // Update Database status = updateDatabase(conf, isAdding); if (status.isSuccess()) { // Update Configuration status = updateConfig(conf, isAdding); if(!status.isSuccess()) { updateDatabase(conf, (!isAdding)); } else { // update the listeners Subnet subnetCurr = subnets.get(conf.getIPAddress()); Subnet subnet; if (subnetCurr == null) { subnet = new Subnet(conf); } else { subnet = subnetCurr.clone(); } notifySubnetChange(subnet, isAdding); } } return status; } /** * Adds Subnet configured in GUI or API3 */ @Override public Status addSubnet(SubnetConfig conf) { return this.addRemoveSubnet(conf, true); } @Override public Status removeSubnet(SubnetConfig conf) { return this.addRemoveSubnet(conf, false); } @Override public Status removeSubnet(String name) { if (name.equalsIgnoreCase(DEFAULT_SUBNET_NAME)) { return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed"); } SubnetConfig conf = subnetsConfigList.get(name); if (conf == null) { return new Status(StatusCode.SUCCESS, "Subnet not present"); } return this.addRemoveSubnet(conf, false); } @Override public Status modifySubnet(SubnetConfig conf) { // Sanity check if (conf == null) { return new Status(StatusCode.BADREQUEST, "Invalid Subnet configuration: null"); } // Valid configuration check Status status = conf.validate(); if (!status.isSuccess()) { log.warn(status.getDescription()); return status; } // If a subnet configuration with this name does not exist, consider this is a creation SubnetConfig target = subnetsConfigList.get(conf.getName()); if (target == null) { return this.addSubnet(conf); } // No change if (target.equals(conf)) { return new Status(StatusCode.SUCCESS); } // Check not allowed modifications if (!target.getSubnet().equals(conf.getSubnet())) { return new Status(StatusCode.BADREQUEST, "IP address change is not allowed"); } // Derive the set of node connectors that are being removed Set<NodeConnector> toRemove = target.getNodeConnectors(); toRemove.removeAll(conf.getNodeConnectors()); List<String> nodeConnectorStrings = null; if (!toRemove.isEmpty()) { nodeConnectorStrings = new ArrayList<String>(); for (NodeConnector nc : toRemove) { nodeConnectorStrings.add(nc.toString()); } status = this.removePortsFromSubnet(conf.getName(), nodeConnectorStrings); if (!status.isSuccess()) { return status; } } // Derive the set of node connectors that are being added Set<NodeConnector> toAdd = conf.getNodeConnectors(); toAdd.removeAll(target.getNodeConnectors()); if (!toAdd.isEmpty()) { List<String> nodeConnectorStringRemoved = nodeConnectorStrings; nodeConnectorStrings = new ArrayList<String>(); for (NodeConnector nc : toAdd) { nodeConnectorStrings.add(nc.toString()); } status = this.addPortsToSubnet(conf.getName(), nodeConnectorStrings); if (!status.isSuccess()) { // If any port was removed, add it back as a best recovery effort if (!toRemove.isEmpty()) { this.addPortsToSubnet(conf.getName(), nodeConnectorStringRemoved); } return status; } } // Update Configuration subnetsConfigList.put(conf.getName(), conf); return new Status(StatusCode.SUCCESS); } @Override public Status addPortsToSubnet(String name, List<String> switchPorts) { if (name == null) { return new Status(StatusCode.BADREQUEST, "Null subnet name"); } SubnetConfig confCurr = subnetsConfigList.get(name); if (confCurr == null) { return new Status(StatusCode.NOTFOUND, "Subnet does not exist"); } if (switchPorts == null || switchPorts.isEmpty()) { return new Status(StatusCode.BADREQUEST, "Null or empty port set"); } Subnet subCurr = subnets.get(confCurr.getIPAddress()); if (subCurr == null) { log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress()); return new Status(StatusCode.NOTFOUND, "Subnet does not exist"); } // Update Database Subnet sub = subCurr.clone(); Set<NodeConnector> sp = NodeConnector.fromString(switchPorts); sub.addNodeConnectors(sp); boolean subnetsReplaced = subnets.replace(confCurr.getIPAddress(), subCurr, sub); if (!subnetsReplaced) { String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name; return new Status(StatusCode.CONFLICT, msg); } // Update Configuration SubnetConfig conf = confCurr.clone(); conf.addNodeConnectors(switchPorts); boolean configReplaced = subnetsConfigList.replace(name, confCurr, conf); if (!configReplaced) { // TODO: recovery using Transactionality String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name; return new Status(StatusCode.CONFLICT, msg); } return new Status(StatusCode.SUCCESS); } @Override public Status removePortsFromSubnet(String name, List<String> switchPorts) { if (name == null) { return new Status(StatusCode.BADREQUEST, "Null subnet name"); } SubnetConfig confCurr = subnetsConfigList.get(name); if (confCurr == null) { return new Status(StatusCode.NOTFOUND, "Subnet does not exist"); } if (switchPorts == null || switchPorts.isEmpty()) { return new Status(StatusCode.BADREQUEST, "Null or empty port set"); } Subnet subCurr = subnets.get(confCurr.getIPAddress()); if (subCurr == null) { log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress()); return new Status(StatusCode.NOTFOUND, "Subnet does not exist"); } // Validation check Status status = SubnetConfig.validatePorts(switchPorts); if (!status.isSuccess()) { return status; } // Update Database Subnet sub = subCurr.clone(); Set<NodeConnector> sp = NodeConnector.fromString(switchPorts); sub.deleteNodeConnectors(sp); boolean subnetsReplace = subnets.replace(confCurr.getIPAddress(), subCurr, sub); if (!subnetsReplace) { String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name; return new Status(StatusCode.CONFLICT, msg); } // Update Configuration SubnetConfig conf = confCurr.clone(); conf.removeNodeConnectors(switchPorts); boolean result = subnetsConfigList.replace(name, confCurr, conf); if (!result) { // TODO: recovery using Transactionality String msg = "Cluster conflict: Conflict while removing ports from " + conf; return new Status(StatusCode.CONFLICT, msg); } return new Status(StatusCode.SUCCESS); } public String getContainerName() { if (containerName == null) { return GlobalConstants.DEFAULT.toString(); } return containerName; } @Override public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) { // if there are no subnets, return the default subnet if (subnets.size() == 0) { return DEFAULT_SUBNET; } for(Map.Entry<InetAddress,Subnet> subnetEntry : subnets.entrySet()) { if(subnetEntry.getValue().isSubnetOf(networkAddress)) { return subnetEntry.getValue(); } } return null; } @Override public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException { // Perform the class deserialization locally, from inside the package // where the class is defined return ois.readObject(); } private void loadSubnetConfiguration() { for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SUBNETS_FILE_NAME)) { addSubnet((SubnetConfig) conf); } } private void loadSpanConfiguration() { for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SPAN_FILE_NAME)) { addSpanConfig((SpanConfig) conf); } } private void loadSwitchConfiguration() { for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SWITCH_CONFIG_FILE_NAME)) { updateNodeConfig((SwitchConfig) conf); } } @SuppressWarnings("deprecation") @Override public void updateSwitchConfig(SwitchConfig cfgObject) { // update default container only if (!isDefaultContainer) { return; } SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId()); if (sc == null) { if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) { return; } } else { if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) { return; } } boolean modeChange = false; if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) { modeChange = true; } String nodeId = cfgObject.getNodeId(); Node node = Node.fromString(nodeId); Map<String, Property> propMapCurr = nodeProps.get(node); if (propMapCurr == null) { return; } Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr); Property desc = new Description(cfgObject.getNodeDescription()); propMap.put(desc.getName(), desc); Property tier = new Tier(Integer.parseInt(cfgObject.getTier())); propMap.put(tier.getName(), tier); if (!nodeProps.replace(node, propMapCurr, propMap)) { // TODO rollback using Transactionality return; } log.trace("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode()); if (modeChange) { notifyModeChange(node, cfgObject.isProactive()); } } @Override public Status updateNodeConfig(SwitchConfig switchConfig) { Status status = switchConfig.validate(); if (!status.isSuccess()) { return status; } Map<String, Property> updateProperties = switchConfig.getNodeProperties(); ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name); if (mode != null) { if (isDefaultContainer) { if (!mode.isValid()) { return new Status(StatusCode.BADREQUEST, "Invalid Forwarding Mode Value"); } } else { return new Status(StatusCode.NOTACCEPTABLE, "Forwarding Mode modification is allowed only in default container"); } } Description description = (Description) switchConfig.getProperty(Description.propertyName); String nodeId = switchConfig.getNodeId(); Node node = Node.fromString(nodeId); NodeDescription nodeDesc = (this.statisticsManager == null) ? null : this.statisticsManager .getNodeDescription(node); String advertisedDesc = (nodeDesc == null) ? "" : nodeDesc.getDescription(); if (description != null && description.getValue() != null) { if (description.getValue().isEmpty() || description.getValue().equals(advertisedDesc)) { updateProperties.remove(Description.propertyName); switchConfig = new SwitchConfig(nodeId, updateProperties); } else { // check if description is configured or was published by any other node for (Map.Entry<Node, Map<String, Property>> entry : nodeProps.entrySet()) { Node n = entry.getKey(); Description desc = (Description) getNodeProp(n, Description.propertyName); NodeDescription nDesc = (this.statisticsManager == null) ? null : this.statisticsManager .getNodeDescription(n); String advDesc = (nDesc == null) ? "" : nDesc.getDescription(); if ((description.equals(desc) || description.getValue().equals(advDesc)) && !node.equals(n)) { return new Status(StatusCode.CONFLICT, "Node name already in use"); } } } } boolean modeChange = false; SwitchConfig sc = nodeConfigList.get(nodeId); Map<String, Property> prevNodeProperties = new HashMap<String, Property>(); if (sc == null) { if ((mode != null) && mode.isProactive()) { modeChange = true; } if (!updateProperties.isEmpty()) { if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) { return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration"); } } } else { prevNodeProperties = new HashMap<String, Property>(sc.getNodeProperties()); ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name); if (mode == null) { if ((prevMode != null) && (prevMode.isProactive())) { modeChange = true; } } else { if (((prevMode != null) && (prevMode.getValue() != mode.getValue())) || (prevMode == null && mode.isProactive())) { modeChange = true; } } if (updateProperties.isEmpty()) { nodeConfigList.remove(nodeId); } else { if (!nodeConfigList.replace(nodeId, sc, switchConfig)) { return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration"); } } } Map<String, Property> propMapCurr = nodeProps.get(node); if (propMapCurr == null) { return new Status(StatusCode.SUCCESS); } Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr); for (Map.Entry<String, Property> entry : prevNodeProperties.entrySet()) { String prop = entry.getKey(); if (!updateProperties.containsKey(prop)) { if (prop.equals(Description.propertyName)) { if (advertisedDesc != null) { if (!advertisedDesc.isEmpty()) { Property desc = new Description(advertisedDesc); propMap.put(Description.propertyName, desc); } } else { propMap.remove(prop); } continue; } else if (prop.equals(ForwardingMode.name)) { Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING); propMap.put(ForwardingMode.name, defaultMode); continue; } propMap.remove(prop); } } propMap.putAll(updateProperties); if (!nodeProps.replace(node, propMapCurr, propMap)) { // TODO rollback using Transactionality return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration"); } if (modeChange) { notifyModeChange(node, (mode == null) ? false : mode.isProactive()); } return new Status(StatusCode.SUCCESS); } @Override public Status removeNodeConfig(String nodeId) { if ((nodeId == null) || (nodeId.isEmpty())) { return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty."); } Map<String, Property> nodeProperties = getSwitchConfig(nodeId).getNodeProperties(); Node node = Node.fromString(nodeId); Map<String, Property> propMapCurr = nodeProps.get(node); if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) { Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr); for (Map.Entry<String, Property> entry : nodeProperties.entrySet()) { String prop = entry.getKey(); if (prop.equals(Description.propertyName)) { Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps(); if (nodeProp.get(node) != null) { propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName)); continue; } } propMap.remove(prop); } if (!nodeProps.replace(node, propMapCurr, propMap)) { return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration."); } } if (nodeConfigList != null) { nodeConfigList.remove(nodeId); } return new Status(StatusCode.SUCCESS); } @Override public Status saveSwitchConfig() { return saveSwitchConfigInternal(); } public Status saveSwitchConfigInternal() { Status status; short number = 0; status = configurationService.persistConfiguration( new ArrayList<ConfigurationObject>(subnetsConfigList.values()), SUBNETS_FILE_NAME); if (status.isSuccess()) { number++; } else { log.warn("Failed to save subnet gateway configurations: " + status.getDescription()); } status = configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(spanConfigList.values()), SPAN_FILE_NAME); if (status.isSuccess()) { number++; } else { log.warn("Failed to save span port configurations: " + status.getDescription()); } status = configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(nodeConfigList.values()), SWITCH_CONFIG_FILE_NAME); if (status.isSuccess()) { number++; } else { log.warn("Failed to save node configurations: " + status.getDescription()); } if (number == 0) { return new Status(StatusCode.INTERNALERROR, "Save failed"); } if (number < 3) { return new Status(StatusCode.INTERNALERROR, "Partial save failure"); } return status; } @Override public List<SpanConfig> getSpanConfigList() { return new ArrayList<SpanConfig>(spanConfigList.values()); } @Override public Status addSpanConfig(SpanConfig conf) { // Valid config check if (!conf.isValidConfig()) { String msg = "Invalid Span configuration"; log.warn(msg); return new Status(StatusCode.BADREQUEST, msg); } // Presence check if (spanConfigList.containsKey(conf)) { return new Status(StatusCode.CONFLICT, "Same span config exists"); } // Update configuration if (spanConfigList.putIfAbsent(conf, conf) == null) { // Update database and notify clients addSpanPorts(conf.getNode(), conf.getPortArrayList()); } return new Status(StatusCode.SUCCESS); } @Override public Status removeSpanConfig(SpanConfig conf) { removeSpanPorts(conf.getNode(), conf.getPortArrayList()); // Update configuration spanConfigList.remove(conf); return new Status(StatusCode.SUCCESS); } @Override public List<NodeConnector> getSpanPorts(Node node) { List<NodeConnector> ncList = new ArrayList<NodeConnector>(); for (NodeConnector nodeConnector : spanNodeConnectors) { if (nodeConnector.getNode().equals(node)) { ncList.add(nodeConnector); } } return ncList; } private void addNode(Node node, Set<Property> props) { log.trace("{} added, props: {}", node, props); if (nodeProps == null) { return; } Map<String, Property> propMapCurr = nodeProps.get(node); Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>() : new HashMap<String, Property>(propMapCurr); // copy node properties from plugin if (props != null) { for (Property prop : props) { propMap.put(prop.getName(), prop); } } boolean forwardingModeChanged = false; // copy node properties from config if (nodeConfigList != null) { String nodeId = node.toString(); SwitchConfig conf = nodeConfigList.get(nodeId); if (conf != null && (conf.getNodeProperties() != null)) { Map<String, Property> nodeProperties = conf.getNodeProperties(); propMap.putAll(nodeProperties); if (nodeProperties.get(ForwardingMode.name) != null) { ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name); forwardingModeChanged = mode.isProactive(); } } } if (!propMap.containsKey(ForwardingMode.name)) { Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING); propMap.put(ForwardingMode.name, defaultMode); } boolean propsAdded = false; // Attempt initial add if (nodeProps.putIfAbsent(node, propMap) == null) { propsAdded = true; /* Notify listeners only for initial node addition * to avoid expensive tasks triggered by redundant notifications */ notifyNode(node, UpdateType.ADDED, propMap); } else { propsAdded = nodeProps.replace(node, propMapCurr, propMap); // check whether forwarding mode changed if (propMapCurr.get(ForwardingMode.name) != null) { ForwardingMode mode = (ForwardingMode) propMapCurr.get(ForwardingMode.name); forwardingModeChanged ^= mode.isProactive(); } } if (!propsAdded) { log.debug("Cluster conflict while adding node {}. Overwriting with latest props: {}", node.getID(), props); addNodeProps(node, propMap); } // check if span ports are configured addSpanPorts(node); // notify proactive mode forwarding if (forwardingModeChanged) { notifyModeChange(node, true); } } private void removeNode(Node node) { log.trace("{} removed", node); if (nodeProps == null) { return; } if (nodeProps.remove(node) == null) { log.debug("Received redundant node REMOVED udate for {}. Skipping..", node); return; } nodeConnectorNames.remove(node); Set<NodeConnector> removeNodeConnectorSet = new HashSet<NodeConnector>(); for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) { NodeConnector nodeConnector = entry.getKey(); if (nodeConnector.getNode().equals(node)) { removeNodeConnectorSet.add(nodeConnector); } } for (NodeConnector nc : removeNodeConnectorSet) { nodeConnectorProps.remove(nc); } // check if span ports need to be cleaned up removeSpanPorts(node); /* notify node listeners */ notifyNode(node, UpdateType.REMOVED, null); } private void updateNode(Node node, Set<Property> props) { log.trace("{} updated, props: {}", node, props); if (nodeProps == null || props == null) { return; } Map<String, Property> propMapCurr = nodeProps.get(node); Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>() : new HashMap<String, Property>(propMapCurr); // copy node properties from plugin String nodeId = node.toString(); for (Property prop : props) { if (nodeConfigList != null) { SwitchConfig conf = nodeConfigList.get(nodeId); if (conf != null && (conf.getNodeProperties() != null) && conf.getNodeProperties().containsKey(prop.getName())) { continue; } } propMap.put(prop.getName(), prop); } if (propMapCurr == null) { if (nodeProps.putIfAbsent(node, propMap) != null) { log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}", node.getID(), props); addNodeProps(node, propMap); } } else { if (!nodeProps.replace(node, propMapCurr, propMap)) { log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}", node.getID(), props); addNodeProps(node, propMap); } } /* notify node listeners */ notifyNode(node, UpdateType.CHANGED, propMap); } @Override public void updateNode(Node node, UpdateType type, Set<Property> props) { log.debug("updateNode: {} type {} props {} for container {}", new Object[] { node, type, props, containerName }); switch (type) { case ADDED: addNode(node, props); break; case CHANGED: updateNode(node, props); break; case REMOVED: removeNode(node); break; default: break; } } @Override public void updateNodeConnector(NodeConnector nodeConnector, UpdateType type, Set<Property> props) { Map<String, Property> propMap = new HashMap<String, Property>(); boolean update = true; log.debug("updateNodeConnector: {} type {} props {} for container {}", new Object[] { nodeConnector, type, props, containerName }); if (nodeConnectorProps == null) { return; } switch (type) { case ADDED: // Skip redundant ADDED update (e.g. cluster switch-over) if (nodeConnectorProps.containsKey(nodeConnector)) { log.debug("Redundant nodeconnector ADDED for {}, props {} for container {}", nodeConnector, props, containerName); update = false; } if (props != null) { for (Property prop : props) { addNodeConnectorProp(nodeConnector, prop); propMap.put(prop.getName(), prop); } } else { addNodeConnectorProp(nodeConnector, null); } addSpanPort(nodeConnector); break; case CHANGED: if (!nodeConnectorProps.containsKey(nodeConnector) || (props == null)) { update = false; } else { for (Property prop : props) { addNodeConnectorProp(nodeConnector, prop); propMap.put(prop.getName(), prop); } } break; case REMOVED: if (!nodeConnectorProps.containsKey(nodeConnector)) { update = false; } removeNodeConnectorAllProps(nodeConnector); // clean up span config removeSpanPort(nodeConnector); break; default: update = false; break; } if (update) { notifyNodeConnector(nodeConnector, type, propMap); } } @Override public Set<Node> getNodes() { return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet()) : new HashSet<Node>(); } @Override public Map<String, Property> getControllerProperties() { return new HashMap<String, Property>(this.controllerProps); } @Override public Property getControllerProperty(String propertyName) { if (propertyName != null) { HashMap<String, Property> propertyMap = new HashMap<String, Property>(this.controllerProps); return propertyMap.get(propertyName); } return null; } @Override public Status setControllerProperty(Property property) { if (property != null) { this.controllerProps.put(property.getName(), property); return new Status(StatusCode.SUCCESS); } return new Status(StatusCode.BADREQUEST, "Invalid property provided when setting property"); } @Override public Status removeControllerProperty(String propertyName) { if (propertyName != null) { if (this.controllerProps.containsKey(propertyName)) { this.controllerProps.remove(propertyName); if (!this.controllerProps.containsKey(propertyName)) { return new Status(StatusCode.SUCCESS); } } String msg = "Unable to remove property " + propertyName + " from Controller"; return new Status(StatusCode.BADREQUEST, msg); } String msg = "Invalid property provided when removing property from Controller"; return new Status(StatusCode.BADREQUEST, msg); } /* * Returns a copy of a list of properties for a given node * * (non-Javadoc) * * @see * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps * (org.opendaylight.controller.sal.core.Node) */ @Override public Map<String, Property> getNodeProps(Node node) { Map<String, Property> rv = new HashMap<String, Property>(); if (this.nodeProps != null) { rv = this.nodeProps.get(node); if (rv != null) { /* make a copy of it */ rv = new HashMap<String, Property>(rv); } } return rv; } @Override public Property getNodeProp(Node node, String propName) { Map<String, Property> propMap = getNodeProps(node); return (propMap != null) ? propMap.get(propName) : null; } @Override public void setNodeProp(Node node, Property prop) { for (int i = 0; i <= REPLACE_RETRY; i++) { /* Get a copy of the property map */ Map<String, Property> propMapCurr = getNodeProps(node); if (propMapCurr == null) { return; } Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr); propMap.put(prop.getName(), prop); if (nodeProps.replace(node, propMapCurr, propMap)) { return; } } log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID()); } @Override public Status removeNodeProp(Node node, String propName) { for (int i = 0; i <= REPLACE_RETRY; i++) { Map<String, Property> propMapCurr = getNodeProps(node); if (propMapCurr != null) { if (!propMapCurr.containsKey(propName)) { return new Status(StatusCode.SUCCESS); } Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr); propMap.remove(propName); if (nodeProps.replace(node, propMapCurr, propMap)) { return new Status(StatusCode.SUCCESS); } } else { return new Status(StatusCode.SUCCESS); } } String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID(); return new Status(StatusCode.CONFLICT, msg); } @Override public Status removeNodeAllProps(Node node) { this.nodeProps.remove(node); return new Status(StatusCode.SUCCESS); } @Override public Set<NodeConnector> getUpNodeConnectors(Node node) { if (nodeConnectorProps == null) { return null; } Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>(); for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) { NodeConnector nodeConnector = entry.getKey(); if (!nodeConnector.getNode().equals(node)) { continue; } if (isNodeConnectorEnabled(nodeConnector)) { nodeConnectorSet.add(nodeConnector); } } return nodeConnectorSet; } @Override public Set<NodeConnector> getNodeConnectors(Node node) { if (nodeConnectorProps == null) { return null; } Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>(); for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) { NodeConnector nodeConnector = entry.getKey(); if (!nodeConnector.getNode().equals(node)) { continue; } nodeConnectorSet.add(nodeConnector); } return nodeConnectorSet; } @Override public Set<NodeConnector> getPhysicalNodeConnectors(Node node) { if (nodeConnectorProps == null) { return null; } Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>(); for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) { NodeConnector nodeConnector = entry.getKey(); if (!nodeConnector.getNode().equals(node) || isSpecial(nodeConnector)) { continue; } nodeConnectorSet.add(nodeConnector); } return nodeConnectorSet; } @Override public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) { Map<String, Property> rv = new HashMap<String, Property>(); if (this.nodeConnectorProps != null) { rv = this.nodeConnectorProps.get(nodeConnector); if (rv != null) { rv = new HashMap<String, Property>(rv); } } return rv; } @Override public Property getNodeConnectorProp(NodeConnector nodeConnector, String propName) { Map<String, Property> propMap = getNodeConnectorProps(nodeConnector); return (propMap != null) ? propMap.get(propName) : null; } private byte[] getHardwareMAC() { Enumeration<NetworkInterface> nis; byte[] macAddress = null; try { nis = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { log.error("Failed to acquire controller MAC: ", e); return macAddress; } while (nis.hasMoreElements()) { NetworkInterface ni = nis.nextElement(); try { macAddress = ni.getHardwareAddress(); } catch (SocketException e) { log.error("Failed to acquire controller MAC: ", e); } if (macAddress != null && macAddress.length != 0) { break; } } if (macAddress == null) { log.warn("Failed to acquire controller MAC: No physical interface found"); // This happens when running controller on windows VM, for example // Try parsing the OS command output } return macAddress; } @Override public byte[] getControllerMAC() { MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name); return (macProperty == null) ? null : macProperty.getMacAddress(); } @Override public NodeConnector getNodeConnector(Node node, String nodeConnectorName) { if (nodeConnectorNames == null) { return null; } Map<String, NodeConnector> map = nodeConnectorNames.get(node); if (map == null) { return null; } return map.get(nodeConnectorName); } /** * Adds a node connector and its property if any * * @param nodeConnector * {@link org.opendaylight.controller.sal.core.NodeConnector} * @param propName * name of {@link org.opendaylight.controller.sal.core.Property} * @return success or failed reason */ @Override public Status addNodeConnectorProp(NodeConnector nodeConnector, Property prop) { Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector); Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>() : new HashMap<String, Property>(propMapCurr); String msg = "Cluster conflict: Unable to add NodeConnector Property."; // Just add the nodeConnector if prop is not available (in a non-default // container) if (prop == null) { if (propMapCurr == null) { if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) { return new Status(StatusCode.CONFLICT, msg); } } else { if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) { return new Status(StatusCode.CONFLICT, msg); } } return new Status(StatusCode.SUCCESS); } propMap.put(prop.getName(), prop); if (propMapCurr == null) { if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) { return new Status(StatusCode.CONFLICT, msg); } } else { if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) { return new Status(StatusCode.CONFLICT, msg); } } if (prop.getName().equals(Name.NamePropName)) { if (nodeConnectorNames != null) { Node node = nodeConnector.getNode(); Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node); Map<String, NodeConnector> map = new HashMap<String, NodeConnector>(); if (mapCurr != null) { for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) { String s = entry.getKey(); try { map.put(s, new NodeConnector(entry.getValue())); } catch (ConstructionException e) { log.error("An error occured",e); } } } map.put(((Name) prop).getValue(), nodeConnector); if (mapCurr == null) { if (nodeConnectorNames.putIfAbsent(node, map) != null) { // TODO: recovery using Transactionality return new Status(StatusCode.CONFLICT, msg); } } else { if (!nodeConnectorNames.replace(node, mapCurr, map)) { // TODO: recovery using Transactionality return new Status(StatusCode.CONFLICT, msg); } } } } return new Status(StatusCode.SUCCESS); } /** * Removes one property of a node connector * * @param nodeConnector * {@link org.opendaylight.controller.sal.core.NodeConnector} * @param propName * name of {@link org.opendaylight.controller.sal.core.Property} * @return success or failed reason */ @Override public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) { Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector); if (propMapCurr == null) { /* Nothing to remove */ return new Status(StatusCode.SUCCESS); } Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr); propMap.remove(propName); boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap); String msg = "Cluster conflict: Unable to remove NodeConnector property."; if (!result) { return new Status(StatusCode.CONFLICT, msg); } if (propName.equals(Name.NamePropName)) { if (nodeConnectorNames != null) { Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName)); if (name != null) { Node node = nodeConnector.getNode(); Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node); if (mapCurr != null) { Map<String, NodeConnector> map = new HashMap<String, NodeConnector>(); for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) { String s = entry.getKey(); try { map.put(s, new NodeConnector(entry.getValue())); } catch (ConstructionException e) { log.error("An error occured",e); } } map.remove(name.getValue()); if (!nodeConnectorNames.replace(node, mapCurr, map)) { // TODO: recovery using Transactionality return new Status(StatusCode.CONFLICT, msg); } } } } } return new Status(StatusCode.SUCCESS); } /** * Removes all the properties of a node connector * * @param nodeConnector * {@link org.opendaylight.controller.sal.core.NodeConnector} * @return success or failed reason */ @Override public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) { if (nodeConnectorNames != null) { Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName)); if (name != null) { Node node = nodeConnector.getNode(); Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node); if (mapCurr != null) { Map<String, NodeConnector> map = new HashMap<String, NodeConnector>(); for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) { String s = entry.getKey(); try { map.put(s, new NodeConnector(entry.getValue())); } catch (ConstructionException e) { log.error("An error occured",e); } } map.remove(name.getValue()); if (map.isEmpty()) { nodeConnectorNames.remove(node); } else { if (!nodeConnectorNames.replace(node, mapCurr, map)) { log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.", nodeConnector.getID()); } } } } } nodeConnectorProps.remove(nodeConnector); return new Status(StatusCode.SUCCESS); } /** * Function called by the dependency manager when all the required * dependencies are satisfied * */ void init(Component c) { Dictionary<?, ?> props = c.getServiceProperties(); if (props != null) { this.containerName = (String) props.get("containerName"); log.trace("Running containerName: {}", this.containerName); } else { // In the Global instance case the containerName is empty this.containerName = ""; } isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT .toString()); } /** * Function called by the dependency manager when at least one dependency * become unsatisfied or when the component is shutting down because for * example bundle is being stopped. * */ void destroy() { shutDown(); } /** * Function called by dependency manager after "init ()" is called and after * the services provided by the class are registered in the service registry * */ void start() { startUp(); /* * Read startup and build database if we are the coordinator */ loadSubnetConfiguration(); loadSpanConfiguration(); loadSwitchConfiguration(); // OSGI console registerWithOSGIConsole(); } /** * Function called after registered the service in OSGi service registry. */ void started() { // solicit for existing inventories getInventories(); } /** * Function called by the dependency manager before the services exported by * the component are unregistered, this will be followed by a "destroy ()" * calls * */ void stop() { } public void setConfigurationContainerService(IConfigurationContainerService service) { log.trace("Got configuration service set request {}", service); this.configurationService = service; } public void unsetConfigurationContainerService(IConfigurationContainerService service) { log.trace("Got configuration service UNset request"); this.configurationService = null; } public void setInventoryService(IInventoryService service) { log.trace("Got inventory service set request {}", service); this.inventoryService = service; // solicit for existing inventories getInventories(); } public void unsetInventoryService(IInventoryService service) { log.trace("Got a service UNset request"); this.inventoryService = null; // clear existing inventories clearInventories(); } public void setStatisticsManager(IStatisticsManager statisticsManager) { log.trace("Got statistics manager set request {}", statisticsManager); this.statisticsManager = statisticsManager; } public void unsetStatisticsManager(IStatisticsManager statisticsManager) { log.trace("Got statistics manager UNset request"); this.statisticsManager = null; } public void setSwitchManagerAware(ISwitchManagerAware service) { log.trace("Got inventory service set request {}", service); if (this.switchManagerAware != null) { this.switchManagerAware.add(service); } // bulk update for newly joined switchManagerAwareNotify(service); } public void unsetSwitchManagerAware(ISwitchManagerAware service) { log.trace("Got a service UNset request"); if (this.switchManagerAware != null) { this.switchManagerAware.remove(service); } } public void setInventoryListener(IInventoryListener service) { log.trace("Got inventory listener set request {}", service); if (this.inventoryListeners != null) { this.inventoryListeners.add(service); } // bulk update for newly joined bulkUpdateService(service); } public void unsetInventoryListener(IInventoryListener service) { log.trace("Got a service UNset request"); if (this.inventoryListeners != null) { this.inventoryListeners.remove(service); } } public void setSpanAware(ISpanAware service) { log.trace("Got SpanAware set request {}", service); if (this.spanAware != null) { this.spanAware.add(service); } // bulk update for newly joined spanAwareNotify(service); } public void unsetSpanAware(ISpanAware service) { log.trace("Got a service UNset request"); if (this.spanAware != null) { this.spanAware.remove(service); } } void setClusterContainerService(IClusterContainerServices s) { log.trace("Cluster Service set"); this.clusterContainerService = s; } void unsetClusterContainerService(IClusterContainerServices s) { if (this.clusterContainerService == s) { log.trace("Cluster Service removed!"); this.clusterContainerService = null; } } private void getInventories() { if (inventoryService == null) { log.trace("inventory service not avaiable"); return; } Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps(); for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) { Node node = entry.getKey(); log.debug("getInventories: {} added for container {}", new Object[] { node, containerName }); Map<String, Property> propMap = entry.getValue(); Set<Property> props = new HashSet<Property>(); for (Property property : propMap.values()) { props.add(property); } addNode(node, props); } Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps(); for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) { Map<String, Property> propMap = entry.getValue(); for (Property property : propMap.values()) { addNodeConnectorProp(entry.getKey(), property); } } } private void clearInventories() { nodeProps.clear(); nodeConnectorProps.clear(); nodeConnectorNames.clear(); spanNodeConnectors.clear(); } private void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) { synchronized (inventoryListeners) { for (IInventoryListener service : inventoryListeners) { service.notifyNode(node, type, propMap); } } } private void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) { synchronized (inventoryListeners) { for (IInventoryListener service : inventoryListeners) { service.notifyNodeConnector(nodeConnector, type, propMap); } } } /* * For those joined late, bring them up-to-date. */ private void switchManagerAwareNotify(ISwitchManagerAware service) { for (Subnet sub : subnets.values()) { service.subnetNotify(sub, true); } for (Node node : getNodes()) { SwitchConfig sc = getSwitchConfig(node.toString()); if ((sc != null) && isDefaultContainer) { ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name); service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive()); } } } private void bulkUpdateService(IInventoryListener service) { Map<String, Property> propMap; UpdateType type = UpdateType.ADDED; for (Node node : getNodes()) { propMap = nodeProps.get(node); service.notifyNode(node, type, propMap); } for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) { NodeConnector nodeConnector = entry.getKey(); propMap = nodeConnectorProps.get(nodeConnector); service.notifyNodeConnector(nodeConnector, type, propMap); } } private void spanAwareNotify(ISpanAware service) { for (Node node : getNodes()) { for (SpanConfig conf : getSpanConfigList(node)) { service.spanUpdate(node, conf.getPortArrayList(), true); } } } private void registerWithOSGIConsole() { BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()) .getBundleContext(); bundleContext.registerService(CommandProvider.class.getName(), this, null); } @Override public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) { if (nodeConnector == null) { return false; } Config config = (Config) getNodeConnectorProp(nodeConnector, Config.ConfigPropName); State state = (State) getNodeConnectorProp(nodeConnector, State.StatePropName); return ((config != null) && (config.getValue() == Config.ADMIN_UP) && (state != null) && (state.getValue() == State.EDGE_UP)); } @Override public boolean doesNodeConnectorExist(NodeConnector nc) { return (nc != null && nodeConnectorProps != null && nodeConnectorProps.containsKey(nc)); } @Override public String getHelp() { StringBuffer help = new StringBuffer(); help.append(" help.append("\t pencs <node id> - Print enabled node connectors for a given node\n"); help.append("\t pdm <node id> - Print switch ports in device map\n"); return help.toString(); } public void _pencs(CommandInterpreter ci) { String st = ci.nextArgument(); if (st == null) { ci.println("Please enter node id"); return; } Node node = Node.fromString(st); if (node == null) { ci.println("Please enter node id"); return; } Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node); if (nodeConnectorSet == null) { return; } for (NodeConnector nodeConnector : nodeConnectorSet) { if (nodeConnector == null) { continue; } ci.println(nodeConnector); } ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size()); } public void _pdm(CommandInterpreter ci) { String st = ci.nextArgument(); if (st == null) { ci.println("Please enter node id"); return; } Node node = Node.fromString(st); if (node == null) { ci.println("Please enter node id"); return; } Switch sw = getSwitchByNode(node); ci.println(" NodeConnector Name"); Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors(); String nodeConnectorName; if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) { for (NodeConnector nodeConnector : nodeConnectorSet) { Map<String, Property> propMap = getNodeConnectorProps(nodeConnector); nodeConnectorName = (propMap == null) ? null : ((Name) propMap .get(Name.NamePropName)).getValue(); if (nodeConnectorName != null) { Node nd = nodeConnector.getNode(); if (!nd.equals(node)) { log.debug("node not match {} {}", nd, node); } Map<String, NodeConnector> map = nodeConnectorNames .get(node); if (map != null) { NodeConnector nc = map.get(nodeConnectorName); if (nc == null) { log.debug("no nodeConnector named {}", nodeConnectorName); } else if (!nc.equals(nodeConnector)) { log.debug("nodeConnector not match {} {}", nc, nodeConnector); } } } ci.println(nodeConnector + " " + ((nodeConnectorName == null) ? "" : nodeConnectorName) + "(" + nodeConnector.getID() + ")"); } ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size()); } } @Override public byte[] getNodeMAC(Node node) { MacAddress mac = (MacAddress) this.getNodeProp(node, MacAddress.name); return (mac != null) ? mac.getMacAddress() : null; } @Override public boolean isSpecial(NodeConnector p) { if (p.getType().equals(NodeConnectorIDType.CONTROLLER) || p.getType().equals(NodeConnectorIDType.ALL) || p.getType().equals(NodeConnectorIDType.SWSTACK) || p.getType().equals(NodeConnectorIDType.HWPATH)) { return true; } return false; } /* * Add span configuration to local cache and notify clients */ private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) { List<NodeConnector> ncLists = new ArrayList<NodeConnector>(); for (NodeConnector nodeConnector : nodeConnectors) { if (!spanNodeConnectors.contains(nodeConnector)) { ncLists.add(nodeConnector); } } if (ncLists.size() > 0) { spanNodeConnectors.addAll(ncLists); notifySpanPortChange(node, ncLists, true); } } private void addSpanPorts(Node node) { for (SpanConfig conf : getSpanConfigList(node)) { addSpanPorts(node, conf.getPortArrayList()); } } private void addSpanPort(NodeConnector nodeConnector) { // only add if span is configured on this nodeConnector for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) { if (conf.getPortArrayList().contains(nodeConnector)) { List<NodeConnector> ncList = new ArrayList<NodeConnector>(); ncList.add(nodeConnector); addSpanPorts(nodeConnector.getNode(), ncList); return; } } } /* * Remove span configuration to local cache and notify clients */ private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) { List<NodeConnector> ncLists = new ArrayList<NodeConnector>(); for (NodeConnector nodeConnector : nodeConnectors) { if (spanNodeConnectors.contains(nodeConnector)) { ncLists.add(nodeConnector); } } if (ncLists.size() > 0) { spanNodeConnectors.removeAll(ncLists); notifySpanPortChange(node, ncLists, false); } } private void removeSpanPorts(Node node) { for (SpanConfig conf : getSpanConfigList(node)) { addSpanPorts(node, conf.getPortArrayList()); } } private void removeSpanPort(NodeConnector nodeConnector) { if (spanNodeConnectors.contains(nodeConnector)) { List<NodeConnector> ncLists = new ArrayList<NodeConnector>(); ncLists.add(nodeConnector); removeSpanPorts(nodeConnector.getNode(), ncLists); } } private void addNodeProps(Node node, Map<String, Property> propMap) { if (propMap == null) { propMap = new HashMap<String, Property>(); } nodeProps.put(node, propMap); } @Override public Status saveConfiguration() { return saveSwitchConfig(); } /** * Creates a Name/Tier/Bandwidth/MacAddress(controller property) Property * object based on given property name and value. Other property types are * not supported yet. * * @param propName * Name of the Property * @param propValue * Value of the Property * @return {@link org.opendaylight.controller.sal.core.Property} */ @Override public Property createProperty(String propName, String propValue) { if (propName == null) { log.debug("propName is null"); return null; } if (propValue == null) { log.debug("propValue is null"); return null; } try { if (propName.equalsIgnoreCase(Description.propertyName)) { return new Description(propValue); } else if (propName.equalsIgnoreCase(Tier.TierPropName)) { int tier = Integer.parseInt(propValue); return new Tier(tier); } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) { long bw = Long.parseLong(propValue); return new Bandwidth(bw); } else if (propName.equalsIgnoreCase(ForwardingMode.name)) { int mode = Integer.parseInt(propValue); return new ForwardingMode(mode); } else if (propName.equalsIgnoreCase(MacAddress.name)){ return new MacAddress(propValue); } else { log.debug("Not able to create {} property", propName); } } catch (Exception e) { log.debug("createProperty caught exception {}", e.getMessage()); } return null; } @SuppressWarnings("deprecation") @Override public String getNodeDescription(Node node) { // Check first if user configured a name SwitchConfig config = getSwitchConfig(node.toString()); if (config != null) { String configuredDesc = config.getNodeDescription(); if (configuredDesc != null && !configuredDesc.isEmpty()) { return configuredDesc; } } // No name configured by user, get the node advertised name Description desc = (Description) getNodeProp(node, Description.propertyName); return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? "" : desc.getValue(); } @Override public Set<Switch> getConfiguredNotConnectedSwitches() { Set<Switch> configuredNotConnectedSwitches = new HashSet<Switch>(); if (this.inventoryService == null) { log.trace("inventory service not available"); return configuredNotConnectedSwitches; } Set<Node> configuredNotConnectedNodes = this.inventoryService.getConfiguredNotConnectedNodes(); if (configuredNotConnectedNodes != null) { for (Node node : configuredNotConnectedNodes) { Switch sw = getSwitchByNode(node); configuredNotConnectedSwitches.add(sw); } } return configuredNotConnectedSwitches; } }
package com.sli.portlet.action; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletConfig; import javax.portlet.PortletException; import javax.portlet.ProcessAction; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.servlet.http.HttpSession; import javax.xml.namespace.QName; import com.liferay.portal.kernel.util.HttpUtil; import org.slc.sli.json.bean.AppsData; import org.slc.sli.json.bean.UserData; import org.slc.sli.util.AppsUtil; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.servlet.SessionMessages; import com.liferay.portal.kernel.util.JavaConstants; import com.liferay.portal.util.PortalUtil; import com.liferay.util.bridges.mvc.MVCPortlet; import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portal.kernel.util.PropsUtil; import com.sli.util.PropsKeys; /** * Portlet implementation class AppSelectionInterfacePortlet */ public class AdminAppSelectionInterfacePortlet extends MVCPortlet { @Override public void render(RenderRequest renderRequest, RenderResponse renderResponse) throws PortletException, IOException { HttpSession session = PortalUtil.getHttpServletRequest(renderRequest) .getSession(false); String tokenFromReq = (String) session.getAttribute("OAUTH_TOKEN"); _log.info(tokenFromReq); // String token = "e88cb6d1-771d-46ac-a207-2e58d7f12196"; // check whether user is admin user or not UserData userdata = AppsUtil.getUserData(tokenFromReq); boolean isAdmin = AppsUtil.isAdmin(userdata); _log.info("is admin " + isAdmin); if (isAdmin) { try{ List<AppsData> appsData = AppsUtil.getUserApps(tokenFromReq); List<AppsData> tempAppsData = new ArrayList<AppsData>(appsData); //DE505- checked current url and removed from list String currUrl = "https://"+renderRequest.getServerName()+"/portal"; _log.info("current url---"+currUrl); for(AppsData apps : tempAppsData){ if(apps.getApplication_url().contains(currUrl)){ appsData.remove(apps); } } renderRequest.setAttribute("appList", appsData); }catch (Exception e) { _log.info("json response is null"); } } super.render(renderRequest, renderResponse); } /** * <b> This method process wsrl action and opens wsrp page with appropriate * wsrp portlet</b> * * @param actionRequest * @param actionResponse * @throws IOException * @throws PortletException */ @ProcessAction(name = "openwsrppage") public void processWsrpAction(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException { String url = actionRequest.getParameter("url"); actionResponse.setEvent(new QName("http:sli.com/events", "wsrpurl"), url); String wsrpPage = GetterUtil.getString(PropsUtil .get(PropsKeys.WSRP_PAGE)); // Hide default success Message PortletConfig portletConfig = (PortletConfig) actionRequest .getAttribute(JavaConstants.JAVAX_PORTLET_CONFIG); SessionMessages.add(actionRequest, portletConfig.getPortletName() + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE); actionResponse.sendRedirect(wsrpPage); } /** * <b> This method process Iframe action and opens Iframe page with proper * url</b> * * @param actionRequest * @param actionResponse * @throws IOException * @throws PortletException */ @ProcessAction(name = "openiframepage") public void processIframeAction(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException { String url = actionRequest.getParameter("url"); URL appUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection)appUrl.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int code = connection.getResponseCode(); _log.info("code============"+code); // Hide default success Message PortletConfig portletConfig = (PortletConfig) actionRequest .getAttribute(JavaConstants.JAVAX_PORTLET_CONFIG); SessionMessages.add(actionRequest, portletConfig.getPortletName() + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE); if(code == 200){ String encodedUrl = ""; //DE 660 - Encoded url in iframe page. encodedUrl = HttpUtil.encodeURL(url); //encodedUrl = URLEncoder.encode(url.toString(),"UTF-8"); _log.info("encoded url===== "+encodedUrl); actionResponse.setEvent(new QName("http:sli.com/events", "iframeurl"),encodedUrl); String iframePage = GetterUtil.getString(PropsUtil .get(PropsKeys.IFRAME_PAGE)); actionResponse.sendRedirect(iframePage + "#" + encodedUrl); }else{ actionResponse.sendRedirect("/portal/web/guest/error"); } } private static Log _log = LogFactoryUtil .getLog(AdminAppSelectionInterfacePortlet.class); }
package at.pointhi.irbuilder.irwriter.visitors.instruction; import com.oracle.truffle.llvm.parser.model.blocks.InstructionBlock; import com.oracle.truffle.llvm.parser.model.enums.AtomicOrdering; import com.oracle.truffle.llvm.parser.model.enums.BinaryOperator; import com.oracle.truffle.llvm.parser.model.enums.Flag; import com.oracle.truffle.llvm.parser.model.enums.SynchronizationScope; import com.oracle.truffle.llvm.parser.model.functions.FunctionDeclaration; import com.oracle.truffle.llvm.parser.model.functions.FunctionDefinition; import com.oracle.truffle.llvm.parser.model.functions.FunctionParameter; import com.oracle.truffle.llvm.parser.model.symbols.constants.Constant; import com.oracle.truffle.llvm.parser.model.symbols.constants.integer.IntegerConstant; import com.oracle.truffle.llvm.parser.model.symbols.instructions.AllocateInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.BinaryOperationInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.BranchInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.Call; import com.oracle.truffle.llvm.parser.model.symbols.instructions.CallInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.CastInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.CompareExchangeInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.CompareInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.ConditionalBranchInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.ExtractElementInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.ExtractValueInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.GetElementPointerInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.IndirectBranchInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.InsertElementInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.InsertValueInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.Invoke; import com.oracle.truffle.llvm.parser.model.symbols.instructions.InvokeInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.LandingpadInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.LoadInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.PhiInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.ResumeInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.ReturnInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.SelectInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.ShuffleVectorInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.StoreInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.SwitchInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.SwitchOldInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.UnreachableInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.VoidCallInstruction; import com.oracle.truffle.llvm.parser.model.symbols.instructions.VoidInvokeInstruction; import com.oracle.truffle.llvm.parser.model.visitors.InstructionVisitor; import com.oracle.truffle.llvm.runtime.types.FunctionType; import com.oracle.truffle.llvm.runtime.types.PointerType; import com.oracle.truffle.llvm.runtime.types.Type; import com.oracle.truffle.llvm.runtime.types.VectorType; import com.oracle.truffle.llvm.runtime.types.VoidType; import com.oracle.truffle.llvm.runtime.types.symbols.Symbol; import com.oracle.truffle.llvm.runtime.types.symbols.ValueSymbol; import at.pointhi.irbuilder.irwriter.IRWriter; import at.pointhi.irbuilder.irwriter.IRWriterVersion; import at.pointhi.irbuilder.irwriter.visitors.IRWriterBaseVisitor; public class IRWriterInstructionVisitor extends IRWriterBaseVisitor implements InstructionVisitor { public IRWriterInstructionVisitor(IRWriterVersion.IRWriterVisitors visitors, IRWriter.PrintTarget target) { super(visitors, target); } protected static final String LLVMIR_LABEL_ALIGN = "align"; protected static final String INDENTATION = " "; protected void writeIndent() { write(INDENTATION); } private static final String LLVMIR_LABEL_ALLOCATE = "alloca"; @Override public void visit(AllocateInstruction allocate) { writeIndent(); // <result> = alloca <type> writef("%s = %s ", allocate.getName(), LLVMIR_LABEL_ALLOCATE); writeType(allocate.getPointeeType()); // [, <ty> <NumElements>] if (!(allocate.getCount() instanceof IntegerConstant && ((IntegerConstant) allocate.getCount()).getValue() == 1)) { write(", "); writeType(allocate.getCount().getType()); write(" "); writeInnerSymbolValue(allocate.getCount()); } // [, align <alignment>] if (allocate.getAlign() != 0) { writef(", %s %d", LLVMIR_LABEL_ALIGN, 1 << (allocate.getAlign() - 1)); } writeln(); } @Override public void visit(BinaryOperationInstruction operation) { writeIndent(); // <result> = <op> writef("%s = %s ", operation.getName(), operation.getOperator().getIrString()); // { <flag>}* for (Flag flag : operation.getFlags()) { write(flag.getIrString()); write(" "); } // <ty> <op1>, <op2> writeType(operation.getType()); write(" "); writeInnerSymbolValue(operation.getLHS()); write(", "); writeInnerSymbolValue(operation.getRHS()); writeln(); } private static final String LLVMIR_LABEL_BRANCH = "br"; private static final String LLVMIR_LABEL_BRANCH_LABEL = "label"; @Override public void visit(BranchInstruction branch) { writeIndent(); writef("%s %s ", LLVMIR_LABEL_BRANCH, LLVMIR_LABEL_BRANCH_LABEL); writeBlockName(branch.getSuccessor()); writeln(); } protected static final String LLVMIR_LABEL_CALL = "call"; @Override public void visit(CallInstruction call) { writeIndent(); // <result> = write(call.getName()); write(" = "); // [tail] call write(LLVMIR_LABEL_CALL); write(" "); writeFunctionCall(call); writeln(); } @Override public void visit(CastInstruction cast) { writeIndent(); writef("%s = %s ", cast.getName(), cast.getOperator().getIrString()); writeType(cast.getValue().getType()); write(" "); writeInnerSymbolValue(cast.getValue()); write(" to "); writeType(cast.getType()); writeln(); } protected static final String LLVMIR_LABEL_COMPARE_EXCHANGE = "cmpxchg"; @Override public void visit(CompareExchangeInstruction cmpxchg) { writeIndent(); write(cmpxchg.getName()); write(" = "); write(LLVMIR_LABEL_COMPARE_EXCHANGE); if (cmpxchg.isVolatile()) { write(" volatile"); } write(" "); writeType(cmpxchg.getPtr().getType()); write(" "); writeInnerSymbolValue(cmpxchg.getPtr()); write(", "); writeSymbolType(cmpxchg.getCmp()); write(" "); writeInnerSymbolValue(cmpxchg.getCmp()); write(", "); writeSymbolType(cmpxchg.getReplace()); write(" "); writeInnerSymbolValue(cmpxchg.getReplace()); if (cmpxchg.getSynchronizationScope().equals(SynchronizationScope.SINGLE_THREAD)) { write(" singlethread"); } write(" "); write(cmpxchg.getSuccessOrdering().getIrString()); writeln(); } private static final String LLVMIR_LABEL_COMPARE = "icmp"; private static final String LLVMIR_LABEL_COMPARE_FP = "fcmp"; @Override public void visit(CompareInstruction operation) { writeIndent(); // <result> = <icmp|fcmp> <cond> <ty> <op1>, <op2> write(operation.getName()); write(" = "); if (operation.getOperator().isFloatingPoint()) { write(LLVMIR_LABEL_COMPARE_FP); } else { write(LLVMIR_LABEL_COMPARE); } write(" "); write(operation.getOperator().getIrString()); write(" "); writeType(operation.getLHS().getType()); write(" "); writeInnerSymbolValue(operation.getLHS()); write(", "); writeInnerSymbolValue(operation.getRHS()); writeln(); } private static final String LLVMIR_LABEL_CONDITIONAL_BRANCH = "br"; @Override public void visit(ConditionalBranchInstruction branch) { writeIndent(); // br i1 <cond>, label <iftrue>, label <iffalse> write(LLVMIR_LABEL_CONDITIONAL_BRANCH); write(" "); writeType(branch.getCondition().getType()); write(" "); writeInnerSymbolValue(branch.getCondition()); write(", "); write(LLVMIR_LABEL_BRANCH_LABEL); write(" "); writeBlockName(branch.getTrueSuccessor()); write(", "); write(LLVMIR_LABEL_BRANCH_LABEL); write(" "); writeBlockName(branch.getFalseSuccessor()); writeln(); } private static final String LLVMIR_LABEL_EXTRACT_ELEMENT = "extractelement"; @Override public void visit(ExtractElementInstruction extract) { writeIndent(); // <result> = extractelement <n x <ty>> <val>, i32 <idx> write(extract.getName()); write(" = "); write(LLVMIR_LABEL_EXTRACT_ELEMENT); write(" "); writeType(extract.getVector().getType()); write(" "); writeInnerSymbolValue(extract.getVector()); write(", "); writeType(extract.getIndex().getType()); write(" "); writeInnerSymbolValue(extract.getIndex()); writeln(); } private static final String LLVMIR_LABEL_EXTRACT_VALUE = "extractvalue"; @Override public void visit(ExtractValueInstruction extract) { writeIndent(); /* * TODO: not perfect, but should detect most of the hacked occurrences for * CompareExchangeInstructions correctly. * * This code is required, because Sulong is inserting a ExtractValueInstruction after a * CompareExchangeInstruction, which would be invalid LLVM IR in our case. */ if (extract.getAggregate() instanceof CompareExchangeInstruction) { writeAssignment(extract.getAggregate(), extract, extract.getType()); // write original instruction as comment write(" ;"); } // <result> = extractvalue <aggregate type> <val>, <idx>{, <idx>}* write(extract.getName()); write(" = "); write(LLVMIR_LABEL_EXTRACT_VALUE); write(" "); writeType(extract.getAggregate().getType()); write(" "); writeInnerSymbolValue(extract.getAggregate()); writef(", %d", extract.getIndex()); writeln(); } protected static final String LLVMIR_LABEL_GET_ELEMENT_POINTER = "getelementptr"; protected static final String LLVMIR_LABEL_GET_ELEMENT_POINTER_INBOUNDS = "inbounds"; @Override public void visit(GetElementPointerInstruction gep) { writeIndent(); // <result> = getelementptr writef("%s = %s ", gep.getName(), LLVMIR_LABEL_GET_ELEMENT_POINTER); // [inbounds] if (gep.isInbounds()) { write(LLVMIR_LABEL_GET_ELEMENT_POINTER_INBOUNDS); write(" "); } // <pty>* <ptrval> writeType(gep.getBasePointer().getType()); write(" "); writeInnerSymbolValue(gep.getBasePointer()); // {, <ty> <idx>}* for (final Symbol sym : gep.getIndices()) { write(", "); writeType(sym.getType()); write(" "); writeInnerSymbolValue(sym); } writeln(); } private static final String LLVMIR_LABEL_INDIRECT_BRANCH = "indirectbr"; @Override public void visit(IndirectBranchInstruction branch) { writeIndent(); // indirectbr <somety>* <address>, [ label <dest1>, label <dest2>, ... ] write(LLVMIR_LABEL_INDIRECT_BRANCH); write(" "); writeType(branch.getAddress().getType()); write(" "); writeInnerSymbolValue(branch.getAddress()); write(", [ "); for (int i = 0; i < branch.getSuccessorCount(); i++) { if (i != 0) { write(", "); } write(LLVMIR_LABEL_BRANCH_LABEL); write(" "); writeBlockName(branch.getSuccessor(i)); } write(" ]"); writeln(); } private static final String LLVMIR_LABEL_INSERT_ELEMENT = "insertelement"; @Override public void visit(InsertElementInstruction insert) { writeIndent(); // <result> = insertelement <n x <ty>> <val>, <ty> <elt>, i32 <idx> write(insert.getName()); write(" = "); write(LLVMIR_LABEL_INSERT_ELEMENT); write(" "); writeType(insert.getVector().getType()); write(" "); writeInnerSymbolValue(insert.getVector()); write(", "); writeType(insert.getValue().getType()); write(" "); writeInnerSymbolValue(insert.getValue()); write(", "); writeType(insert.getIndex().getType()); write(" "); writeInnerSymbolValue(insert.getIndex()); writeln(); } private static final String LLVMIR_LABEL_INSERT_VALUE = "insertvalue"; @Override public void visit(InsertValueInstruction insert) { writeIndent(); // <result> = insertvalue <aggregate type> <val>, <ty> <elt>, <idx>{, <idx>}* write(insert.getName()); write(" = "); write(LLVMIR_LABEL_INSERT_VALUE); write(" "); writeType(insert.getAggregate().getType()); write(" "); writeInnerSymbolValue(insert.getAggregate()); write(", "); writeType(insert.getValue().getType()); write(" "); writeInnerSymbolValue(insert.getValue()); writef(", %d", insert.getIndex()); writeln(); } protected static final String LLVMIR_LABEL_LOAD = "load"; protected static final String LLVMIR_LABEL_ATOMIC = "atomic"; protected static final String LLVMIR_LABEL_VOLATILE = "volatile"; protected static final String LLVMIR_LABEL_SINGLETHREAD = "singlethread"; @Override public void visit(LoadInstruction load) { writeIndent(); write(load.getName()); write(" = "); write(LLVMIR_LABEL_LOAD); if (load.getAtomicOrdering() != AtomicOrdering.NOT_ATOMIC) { write(" "); write(LLVMIR_LABEL_ATOMIC); } if (load.isVolatile()) { write(" "); write(LLVMIR_LABEL_VOLATILE); } write(" "); writeType(load.getSource().getType()); write(" "); writeInnerSymbolValue(load.getSource()); if (load.getAtomicOrdering() != AtomicOrdering.NOT_ATOMIC) { if (load.getSynchronizationScope() == SynchronizationScope.SINGLE_THREAD) { write(" "); write(LLVMIR_LABEL_SINGLETHREAD); } write(" "); write(load.getAtomicOrdering().toString()); } if (load.getAlign() != 0) { writef(", %s %d", LLVMIR_LABEL_ALIGN, 1 << (load.getAlign() - 1)); } writeln(); } private static final String LLVMIR_LABEL_PHI = "phi"; @Override public void visit(PhiInstruction phi) { writeIndent(); // <result> = phi <ty> write(phi.getName()); write(" = "); write(LLVMIR_LABEL_PHI); write(" "); writeType(phi.getType()); write(" "); // [ <val0>, <label0>], ... for (int i = 0; i < phi.getSize(); i++) { if (i != 0) { write(", "); } write("[ "); writeInnerSymbolValue(phi.getValue(i)); write(", "); writeBlockName(phi.getBlock(i)); write(" ]"); } writeln(); } private static final String LLVMIR_LABEL_RETURN = "ret"; @Override public void visit(ReturnInstruction ret) { writeIndent(); write(LLVMIR_LABEL_RETURN); write(" "); final Symbol value = ret.getValue(); if (value == null) { writeType(VoidType.INSTANCE); } else { writeSymbolType(value); write(" "); writeInnerSymbolValue(value); } writeln(); } private static final String LLVMIR_LABEL_SELECT = "select"; @Override public void visit(SelectInstruction select) { writeIndent(); // <result> = select selty <cond>, <ty> <val1>, <ty> <val2> write(select.getName()); write(" = "); write(LLVMIR_LABEL_SELECT); write(" "); writeType(select.getCondition().getType()); write(" "); writeInnerSymbolValue(select.getCondition()); write(", "); writeType(select.getTrueValue().getType()); write(" "); writeInnerSymbolValue(select.getTrueValue()); write(", "); writeType(select.getFalseValue().getType()); write(" "); writeInnerSymbolValue(select.getFalseValue()); writeln(); } private static final String LLVMIR_LABEL_SHUFFLE_VECTOR = "shufflevector"; @Override public void visit(ShuffleVectorInstruction shuffle) { writeIndent(); // <result> = shufflevector <n x <ty>> <v1>, <n x <ty>> <v2>, <m x i32> <mask> write(shuffle.getName()); write(" = "); write(LLVMIR_LABEL_SHUFFLE_VECTOR); write(" "); writeType(shuffle.getVector1().getType()); write(" "); writeInnerSymbolValue(shuffle.getVector1()); write(", "); writeType(shuffle.getVector2().getType()); write(" "); writeInnerSymbolValue(shuffle.getVector2()); write(", "); writeType(shuffle.getMask().getType()); write(" "); writeInnerSymbolValue(shuffle.getMask()); writeln(); } private static final String LLVMIR_LABEL_STORE = "store"; @Override public void visit(StoreInstruction store) { writeIndent(); writef("%s ", LLVMIR_LABEL_STORE); if (store.getAtomicOrdering() != AtomicOrdering.NOT_ATOMIC) { write(LLVMIR_LABEL_ATOMIC); write(" "); } if (store.isVolatile()) { write(LLVMIR_LABEL_VOLATILE); write(" "); } writeType(((PointerType) store.getDestination().getType()).getPointeeType()); write(" "); writeInnerSymbolValue(store.getSource()); write(", "); writeType(store.getDestination().getType()); write(" "); writeInnerSymbolValue(store.getDestination()); if (store.getAtomicOrdering() != AtomicOrdering.NOT_ATOMIC) { if (store.getSynchronizationScope() == SynchronizationScope.SINGLE_THREAD) { write(" "); write(LLVMIR_LABEL_SINGLETHREAD); } write(" "); write(store.getAtomicOrdering().getIrString()); } if (store.getAlign() != 0) { writef(", %s %d", LLVMIR_LABEL_ALIGN, 1 << (store.getAlign() - 1)); } writeln(); } private static final String LLVMIR_LABEL_SWITCH = "switch"; @Override public void visit(SwitchInstruction select) { writeIndent(); // switch <intty> <value>, label <defaultdest> write(LLVMIR_LABEL_SWITCH); write(" "); writeType(select.getCondition().getType()); write(" "); writeInnerSymbolValue(select.getCondition()); write(", "); write(LLVMIR_LABEL_BRANCH_LABEL); write(" "); writeBlockName(select.getDefaultBlock()); write(" [ "); for (int i = 0; i < select.getCaseCount(); i++) { if (i != 0) { writeln(); writeIndent(); writeIndent(); } final Symbol val = select.getCaseValue(i); final InstructionBlock blk = select.getCaseBlock(i); writeType(val.getType()); write(" "); writeInnerSymbolValue(val); write(", "); write(LLVMIR_LABEL_BRANCH_LABEL); write(" "); writeBlockName(blk); } write(" ]"); writeln(); } private static final String LLVMIR_LABEL_SWITCH_OLD = "switch"; @Override public void visit(SwitchOldInstruction select) { writeIndent(); // switch <intty> <value>, label <defaultdest> write(LLVMIR_LABEL_SWITCH_OLD); write(" "); writeType(select.getCondition().getType()); write(" "); writeInnerSymbolValue(select.getCondition()); write(", "); write(LLVMIR_LABEL_BRANCH_LABEL); write(" "); writeBlockName(select.getDefaultBlock()); write(" [ "); for (int i = 0; i < select.getCaseCount(); i++) { if (i != 0) { writeln(); writeIndent(); writeIndent(); } writeType(select.getCondition().getType()); write(String.format(" %d, ", select.getCaseValue(i))); write(LLVMIR_LABEL_BRANCH_LABEL); write(" "); writeBlockName(select.getCaseBlock(i)); } write(" ]"); writeln(); } private static final String LLVMIR_LABEL_UNREACHABLE = "unreachable"; @Override public void visit(UnreachableInstruction unreachable) { writeIndent(); write(LLVMIR_LABEL_UNREACHABLE); writeln(); } @Override public void visit(VoidCallInstruction call) { writeIndent(); // [tail] call write(LLVMIR_LABEL_CALL); write(" "); writeFunctionCall(call); writeln(); } private static final String LLVMIR_LABEL_INVOKE = "invoke"; @Override public void visit(InvokeInstruction call) { // <result> = write(call.getName()); write(" = "); // invoke write(LLVMIR_LABEL_INVOKE); write(" "); writeFunctionInvoke(call); writeln(); } @Override public void visit(VoidInvokeInstruction call) { writeIndent(); // invoke write(LLVMIR_LABEL_CALL); write(" "); writeFunctionInvoke(call); writeln(); } private static final String LLVMIR_LABEL_LANDINGPAD = "landingpad"; private static final String LLVMIR_LABEL_LANDINGPAD_CLEANUP = "cleanup"; @Override public void visit(LandingpadInstruction landingpad) { writeIndent(); // <resultval> = write(landingpad.getName()); write(" = "); // landingpad write(LLVMIR_LABEL_LANDINGPAD); write(" "); // <resultty> writeType(landingpad.getType()); // [ cleanup ] if (landingpad.isCleanup()) { write(" "); write(LLVMIR_LABEL_LANDINGPAD_CLEANUP); } // <clause>* // TODO: implement writeln(); } private static final String LLVMIR_LABEL_RESUME = "resume"; @Override public void visit(ResumeInstruction resume) { writeIndent(); write(LLVMIR_LABEL_RESUME); write(" "); writeSymbolType(resume.getValue()); write(" "); writeInnerSymbolValue(resume.getValue()); writeln(); } protected void writeFunctionCall(Call call) { // [cconv] [ret attrs] /* * <ty> * * 'ty': the type of the call instruction itself which is also the type of the return value. * Functions that return no value are marked void. */ writeType(getSymbolType(call)); write(" "); /* * [<fnty>*] * * 'fnty': shall be the signature of the pointer to function value being invoked. The * argument types must match the types implied by this signature. This type can be omitted * if the function is not varargs and if the function type does not return a pointer to a * function. */ final FunctionType funcType = getFunctionType(call.getCallTarget()); final Type retType = funcType.getReturnType(); if (funcType.isVarargs() || (retType instanceof PointerType && ((PointerType) retType).getPointeeType() instanceof FunctionType)) { writeFormalArguments(funcType); write("*"); write(" "); } /* * <fnptrval> * * 'fnptrval': An LLVM value containing a pointer to a function to be invoked. In most * cases, this is a direct function invocation, but indirect calls are just as possible, * calling an arbitrary pointer to function value. */ writeInnerSymbolValue(call.getCallTarget()); /* * (<function args>) * * 'function args': argument list whose types match the function signature argument types * and parameter attributes. All arguments must be of first class type. If the function * signature indicates the function accepts a variable number of arguments, the extra * arguments can be specified. */ writeActualArgs(call); // [fn attrs] } protected void writeFunctionInvoke(Invoke call) { writeType(getSymbolType(call)); write(" "); final FunctionType funcType = getFunctionType(call.getCallTarget()); final Type retType = funcType.getReturnType(); if (funcType.isVarargs() || (retType instanceof PointerType && ((PointerType) retType).getPointeeType() instanceof FunctionType)) { writeFormalArguments(funcType); write("*"); write(" "); } writeInnerSymbolValue(call.getCallTarget()); writeActualArgs(call); } protected static Type getSymbolType(Call call) { if (call instanceof VoidCallInstruction) { return ((VoidCallInstruction) call).getType(); } else if (call instanceof CallInstruction) { return ((CallInstruction) call).getType(); } else { throw new RuntimeException("unexpected type"); } } protected static Type getSymbolType(Invoke call) { if (call instanceof VoidInvokeInstruction) { return ((VoidInvokeInstruction) call).getType(); } else if (call instanceof InvokeInstruction) { return ((InvokeInstruction) call).getType(); } else { throw new RuntimeException("unexpected type"); } } protected static FunctionType getFunctionType(Symbol callTarget) { if (callTarget instanceof FunctionDeclaration) { return ((FunctionDeclaration) callTarget).getType(); } else if (callTarget instanceof FunctionDefinition) { return ((FunctionDefinition) callTarget).getType(); } else if (callTarget instanceof FunctionParameter) { return ((FunctionDefinition) callTarget).getType(); } else if (callTarget instanceof CallInstruction) { Type targetType = ((CallInstruction) callTarget).getType(); targetType = ((PointerType) targetType).getPointeeType(); // TODO: check if (targetType instanceof FunctionType) { return (FunctionType) targetType; } else { throw new AssertionError("unexpected target type: " + targetType.getClass().getName()); } } else if (callTarget instanceof ValueSymbol) { Type targetType; if (callTarget instanceof LoadInstruction) { targetType = ((LoadInstruction) callTarget).getSource().getType(); } else { targetType = callTarget.getType(); } while (targetType instanceof PointerType) { targetType = ((PointerType) targetType).getPointeeType(); } if (targetType instanceof FunctionType) { return (FunctionType) targetType; } else { throw new AssertionError("unexpected target type: " + targetType.getClass().getName()); } } else if (callTarget instanceof Constant) { Type targetType = callTarget.getType(); targetType = ((PointerType) targetType).getPointeeType(); // TODO: check if (targetType instanceof FunctionType) { return (FunctionType) targetType; } else { throw new AssertionError("unexpected target type: " + targetType.getClass().getName()); } } else { throw new AssertionError("unexpected target type: " + callTarget.getClass().getName()); } } protected void writeActualArgs(Call call) { write("("); for (int i = 0; i < call.getArgumentCount(); i++) { final Symbol arg = call.getArgument(i); if (i != 0) { write(", "); } writeSymbolType(arg); write(" "); writeInnerSymbolValue(arg); } write(")"); } protected void writeActualArgs(Invoke call) { write("("); for (int i = 0; i < call.getArgumentCount(); i++) { final Symbol arg = call.getArgument(i); if (i != 0) { write(", "); } writeSymbolType(arg); write(" "); writeInnerSymbolValue(arg); } write(")"); } /** * Write LLVM IR which would be equivalent to an assignment. * * @param from variable we want to assign * @param to resulting variable where we want to place the result * @param type type of the variable which is assigned */ protected void writeAssignment(Symbol from, ValueSymbol to, Type type) { final String tmpPtrName = "%irwriter_tmp_" + to.getName().substring(1); final PointerType tmpPointer = new PointerType(type); write(tmpPtrName); write(" = "); write(LLVMIR_LABEL_ALLOCATE); write(" "); writeType(type); writeln(); writeIndent(); write(LLVMIR_LABEL_STORE); write(" "); writeType(type); write(" "); writeInnerSymbolValue(from); write(", "); writeType(tmpPointer); write(" "); write(tmpPtrName); writeln(); writeIndent(); write(to.getName()); write(" = "); write(LLVMIR_LABEL_LOAD); write(" "); writeType(tmpPointer); write(" "); write(tmpPtrName); } }
package observerPattern; public class ApplicationUser implements User { String city; int price; String venue; Administrator data; public ApplicationUser(Administrator admin) { this.data = admin; this.data.registerUser(this); } public void update(String city, int price, String venue) { } }
package orc.orchard; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.management.ObjectName; import orc.Config; import orc.ast.oil.Expr; import orc.orchard.errors.InvalidJobException; import orc.orchard.errors.InvalidOilException; import orc.orchard.errors.QuotaException; /** * Manage a group of jobs associated with a user account. Note that jobs are * tracked solely in memory, mainly because it would be a hassle to keep the * database up-to-date otherwise. * * @author quark */ public abstract class Account implements AccountMBean { private Map<String, Job> jobs = new HashMap<String, Job>(); private Integer quota = null; private Integer lifespan = null; private boolean canSendMail = false; private boolean canImportJava = false; // NB: right now these limits are hard-coded for all accounts, // because it's too easy to write recursive programs // which take down the server otherwise. private int tokenPoolSize = 1024; private int stackSize = 1024; public Account() {} public void setLifespan(Integer lifespan) { this.lifespan = lifespan; } public void setQuota(Integer quota) { this.quota = quota; } public boolean getCanSendMail() { return canSendMail; } public void setCanSendMail(boolean canSendMail) { this.canSendMail = canSendMail; } public boolean getCanImportJava() { return canImportJava; } public void setCanImportJava(boolean canImportJava) { this.canImportJava = canImportJava; } public synchronized void addJob(final String id, Expr expr) throws QuotaException, InvalidOilException { Config config = new Config(); config.setCapability("send mail", canSendMail); config.setCapability("import java", canImportJava); config.setTokenPoolSize(tokenPoolSize); config.setStackSize(stackSize); if (!canImportJava) { OilSecurityValidator validator = new OilSecurityValidator(); expr.accept(validator); if (validator.hasProblems()) { StringBuffer sb = new StringBuffer(); sb.append("OIL security violations:"); for (OilSecurityValidator.SecurityProblem problem : validator.getProblems()) { sb.append("\n"); sb.append(problem); } throw new InvalidOilException(sb.toString()); } } finishOldJobs(); if (quota != null && jobs.size() >= quota) { throw new QuotaException(); } Job job = new Job(expr, config); job.setStartDate(new Date()); jobs.put(id, job); final ObjectName jmxid = JMXUtilities.newObjectName(job, id); JMXUtilities.registerMBean(job, jmxid); job.onFinish(new Job.FinishListener() { public void finished(Job job) { removeJob(id); JMXUtilities.unregisterMBean(jmxid); } }); } public synchronized Job getJob(String id) throws InvalidJobException { Job out = jobs.get(id); if (out == null) throw new InvalidJobException(); else return out; } public synchronized List<Job> jobs() { return new LinkedList<Job>(jobs.values()); } public synchronized Set<String> getJobIDs() { return new HashSet<String>(jobs.keySet()); } private synchronized void removeJob(String id) { jobs.remove(id); if (jobs.size() == 0) onNoMoreJobs(); } protected abstract void onNoMoreJobs(); public abstract boolean getIsGuest(); public synchronized void finishOldJobs() { if (lifespan == null) return; // find old jobs final int lifespanmillis = lifespan * 1000; Date now = new Date(); LinkedList<Job> old = new LinkedList<Job>(); for (Job job : jobs.values()) { Date death = new Date(job.getStartDate().getTime() + lifespanmillis); if (death.before(now)) { // we can't finish the job now or it will cause // a ConcurrentModificationException when it // removes itself from the active jobs. old.add(job); } } // finish the old jobs we found for (Job job : old) job.finish(); } public synchronized int getNumNewJobs() { int out = 0; for (Job job : jobs.values()) { if (job.getState().equals("NEW")) out++; } return out; } public synchronized int getNumRunningJobs() { int out = 0; for (Job job : jobs.values()) { if (job.getState().equals("RUNNING")) out++; } return out; } public synchronized int getNumBlockedJobs() { int out = 0; for (Job job : jobs.values()) { if (job.getState().equals("BLOCKED")) out++; } return out; } public synchronized int getNumDeadJobs() { int out = 0; for (Job job : jobs.values()) { if (job.getState().equals("DEAD")) out++; } return out; } public Integer getLifespan() { return lifespan; } public Integer getQuota() { return quota; } public int getStackSize() { return stackSize; } public void setStackSize(int stackSize) { this.stackSize = stackSize; } public int getTokenPoolSize() { return tokenPoolSize; } public void setTokenPoolSize(int tokenPoolSize) { this.tokenPoolSize = tokenPoolSize; } }
package raptor.connector.ics; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import raptor.chat.Bugger; import raptor.chat.ChatEvent; import raptor.chat.ChatType; import raptor.chat.Partnership; import raptor.chat.Seek; import raptor.chess.BughouseGame; import raptor.chess.FischerRandomBughouseGame; import raptor.chess.FischerRandomCrazyhouseGame; import raptor.chess.FischerRandomGame; import raptor.chess.Game; import raptor.chess.GameConstants; import raptor.chess.Result; import raptor.chess.SetupGame; import raptor.chess.Variant; import raptor.chess.pgn.PgnHeader; import raptor.connector.ics.bughouse.BugWhoGParser; import raptor.connector.ics.bughouse.BugWhoPParser; import raptor.connector.ics.bughouse.BugWhoUParser; import raptor.connector.ics.chat.AbortRequestedEventParser; import raptor.connector.ics.chat.BugWhoAllEventParser; import raptor.connector.ics.chat.CShoutEventParser; import raptor.connector.ics.chat.ChallengeEventParser; import raptor.connector.ics.chat.ChannelTellEventParser; import raptor.connector.ics.chat.ChatEventParser; import raptor.connector.ics.chat.DrawOfferedEventParser; import raptor.connector.ics.chat.FingerEventParser; import raptor.connector.ics.chat.FollowingEventParser; import raptor.connector.ics.chat.GamesEventParser; import raptor.connector.ics.chat.HistoryEventParser; import raptor.connector.ics.chat.JournalEventParser; import raptor.connector.ics.chat.KibitzEventParser; import raptor.connector.ics.chat.PartnerTellEventParser; import raptor.connector.ics.chat.PartnershipCreatedEventParser; import raptor.connector.ics.chat.PartnershipEndedEventParser; import raptor.connector.ics.chat.QTellParser; import raptor.connector.ics.chat.ShoutEventParser; import raptor.connector.ics.chat.TellEventParser; import raptor.connector.ics.chat.ToldEventParser; import raptor.connector.ics.chat.WhisperEventParser; import raptor.connector.ics.game.message.B1Message; import raptor.connector.ics.game.message.G1Message; import raptor.connector.ics.game.message.GameEndMessage; import raptor.connector.ics.game.message.IllegalMoveMessage; import raptor.connector.ics.game.message.MovesMessage; import raptor.connector.ics.game.message.NoLongerExaminingGameMessage; import raptor.connector.ics.game.message.RemovingObsGameMessage; import raptor.connector.ics.game.message.Style12Message; import raptor.pref.PreferenceKeys; import raptor.service.GameService; import raptor.service.GameService.Offer; import raptor.service.GameService.Offer.OfferType; import raptor.util.RaptorStringTokenizer; /** * An implementation of IcsParser that is both BICS and FICS friendly. */ public class IcsParser implements GameConstants { private static final Log LOG = LogFactory.getLog(IcsParser.class); public static final int MAX_GAME_MESSAGE = 1000; protected B1Parser b1Parser; protected IcsConnector connector; protected G1Parser g1Parser; protected GameEndParser gameEndParser; protected IllegalMoveParser illegalMoveParser; protected MovesParser movesParser; protected NoLongerExaminingGameParser noLongerExaminingParser; protected List<ChatEventParser> nonGameEventParsers = new ArrayList<ChatEventParser>( 30); protected RemovingObsGameParser removingObsGameParser; protected FollowingEventParser followingParser; protected Style12Parser style12Parser; protected SoughtParser soughtParser; protected BugWhoGParser bugWhoGParser; protected BugWhoPParser bugWhoPParser; protected BugWhoUParser bugWhoUParser; /** * Used for BICS parsing. Bics sends a B1 right after you make a move then a * style 12 and another B1. This breaks Raptor, since it uses the game * object to keep track of the state. So it is currently being used to * ignore all B1s if the game is zh and its a BICS parser if they were not * preceded by a style 12. */ protected boolean containedStyle12; protected TakebackParser takebackParser; protected boolean isBicsParser = false; /** * A map keyed by game id. Used to temporarily store G1 messages until the * first style 12 message comes along. A new game requires a 12 message as * well as a G1. */ protected Map<String, G1Message> unprocessedG1Messages = new HashMap<String, G1Message>(); /** * A map keyed by game id. Used to temporarily store style12 messages from * newly examined games until the moves message comes along. From the moves * message you can identify the variant and create the game correctly. */ protected Map<String, Style12Message> exaimineGamesWaitingOnMoves = new HashMap<String, Style12Message>(); /** * A map keyed by game id. Used to temporarily store style12 messages from * newly examined games until the moves message comes along. From the moves * message you can identify the variant and create the game correctly. */ protected Map<String, B1Message> exaimineB1sWaitingOnMoves = new HashMap<String, B1Message>(); /** * BICS does'nt support the partner board in G1 messages so you have to * resort to this to link the bug games together. */ protected List<String> bugGamesWithoutBoard2 = new ArrayList<String>(10); public IcsParser(boolean isBicsParser) { this.isBicsParser = isBicsParser; gameEndParser = new GameEndParser(); b1Parser = new B1Parser(); g1Parser = new G1Parser(); illegalMoveParser = new IllegalMoveParser(); removingObsGameParser = new RemovingObsGameParser(); takebackParser = new TakebackParser(); noLongerExaminingParser = new NoLongerExaminingGameParser(); movesParser = new MovesParser(); followingParser = new FollowingEventParser(); style12Parser = new Style12Parser(); if (!isBicsParser) { soughtParser = new SoughtParser(); bugWhoGParser = new BugWhoGParser(); bugWhoPParser = new BugWhoPParser(); bugWhoUParser = new BugWhoUParser(); } nonGameEventParsers.add(new PartnerTellEventParser()); nonGameEventParsers.add(new ToldEventParser()); nonGameEventParsers.add(new ChannelTellEventParser()); nonGameEventParsers.add(new CShoutEventParser()); nonGameEventParsers.add(new ShoutEventParser()); nonGameEventParsers.add(new KibitzEventParser()); nonGameEventParsers.add(new TellEventParser()); nonGameEventParsers.add(new WhisperEventParser()); nonGameEventParsers.add(new QTellParser()); // Non tell types of events. nonGameEventParsers.add(new ChallengeEventParser()); nonGameEventParsers.add(new PartnershipCreatedEventParser()); nonGameEventParsers.add(new PartnershipEndedEventParser()); nonGameEventParsers.add(new FollowingEventParser()); nonGameEventParsers.add(new DrawOfferedEventParser()); nonGameEventParsers.add(new AbortRequestedEventParser()); nonGameEventParsers.add(new GamesEventParser()); nonGameEventParsers.add(new HistoryEventParser()); nonGameEventParsers.add(new JournalEventParser()); nonGameEventParsers.add(new FingerEventParser()); nonGameEventParsers.add(new BugWhoAllEventParser()); } public ChatEvent[] parse(String inboundMessage) { if (LOG.isDebugEnabled()) { LOG.debug("Raw message in: " + inboundMessage); } List<ChatEvent> events = new ArrayList<ChatEvent>(5); // First handle the Moves message. String afterMovesMessage = parseMovesMessage(inboundMessage, events); if (LOG.isDebugEnabled()) { LOG.debug("After handling moves message: " + afterMovesMessage); } // Next handle game events. if (StringUtils.isNotBlank(afterMovesMessage)) { String afterGameEvents = parseGameEvents(afterMovesMessage); if (LOG.isDebugEnabled()) { LOG.debug("After handling game events: " + afterGameEvents); } // Now process what is left over as chat events. // Don't send it if its only a prompt. if (StringUtils.isNotBlank(afterGameEvents) && !afterGameEvents.trim().equals( connector.getContext().getPrompt())) { // Now process bug who events. ChatEvent bugWhoEvent = processBugWho(afterGameEvents); if (bugWhoEvent == null) { // Now process sought events. ChatEvent soughtEvent = processSought(afterGameEvents); if (soughtEvent == null) { // Its not a game,bugwho,or sought event so now try the // other parsers. for (ChatEventParser parser : nonGameEventParsers) { ChatEvent event = parser.parse(afterGameEvents); if (event != null) { events.add(event); break; } } // Its an unhandled event if (events.isEmpty()) { events.add(new ChatEvent(null, ChatType.UNKNOWN, afterGameEvents)); } } else { events.add(soughtEvent); } } else { events.add(bugWhoEvent); } } } return events.toArray(new ChatEvent[0]); } /** * Invoked when a user is examining a game and it becomes a setup position. */ public void processExaminedGameBecameSetup() { Game[] activeGames = connector.getGameService().getAllActiveGames(); for (Game game : activeGames) { if (game.isInState(Game.EXAMINING_STATE)) { if (LOG.isDebugEnabled()) { LOG .debug("Handling transition from examined game to bsetup."); } SetupGame setupGame = new SetupGame(); game.overwrite(setupGame, true); // Set all the drop pieces. setupGame.setPieceCount(WHITE, PAWN, 1); setupGame.setPieceCount(WHITE, KNIGHT, 1); setupGame.setPieceCount(WHITE, BISHOP, 1); setupGame.setPieceCount(WHITE, ROOK, 1); setupGame.setPieceCount(WHITE, QUEEN, 1); setupGame.setPieceCount(WHITE, KING, 1); setupGame.setPieceCount(BLACK, PAWN, 1); setupGame.setPieceCount(BLACK, KNIGHT, 1); setupGame.setPieceCount(BLACK, BISHOP, 1); setupGame.setPieceCount(BLACK, ROOK, 1); setupGame.setPieceCount(BLACK, QUEEN, 1); setupGame.setPieceCount(BLACK, KING, 1); // Adjust the state since it was cleared after the overwrite. setupGame.clearState(Game.EXAMINING_STATE); setupGame.addState(Game.SETUP_STATE); setupGame.addState(Game.DROPPABLE_STATE); connector.getGameService().addGame(setupGame); connector.getGameService().fireExaminedGameBecameSetup( game.getId()); break; } } } public void setConnector(IcsConnector connector) { this.connector = connector; } protected void adjustBughouseHeadersAndFollowPartnersGamesForBics( Game game, Style12Message message, GameService service) { // BICS currently does'nt set a partner id so you have // do this. if (bugGamesWithoutBoard2.isEmpty()) { if (observePartnerBoardForGame(game)) { bugGamesWithoutBoard2.add(message.gameId); connector.sendMessage("pobserve " + (message.isWhiteOnTop ? message.blackName : message.whiteName), true); } } else { Game otherBoard = service.getGame(bugGamesWithoutBoard2.get(0)); if (otherBoard == null) { connector .onError( "Could not find game with id " + bugGamesWithoutBoard2.get(0) + " in the GameService. Please get BICS to add a partner game id to its G1 message.\n" + " You can complain to both johnthegreat and aramen.", new Exception()); } else { ((BughouseGame) game).setOtherBoard((BughouseGame) otherBoard); ((BughouseGame) otherBoard).setOtherBoard((BughouseGame) game); if (StringUtils.defaultIfEmpty( otherBoard.getHeader(PgnHeader.WhiteOnTop), "0") .equals("0")) { game.setHeader(PgnHeader.WhiteOnTop, "1"); } else { game.setHeader(PgnHeader.WhiteOnTop, "0"); } } bugGamesWithoutBoard2.clear(); } } protected void adjustBughouseHeadersAndFollowPartnersGamesForFics( Game game, G1Message g1Message, Style12Message message, GameService service) { if (!connector.getGameService().isManaging(g1Message.parterGameId)) { if (observePartnerBoardForGame(game)) { connector .sendMessage("observe " + g1Message.parterGameId, true); } } else { Game otherBoard = service.getGame(g1Message.parterGameId); ((BughouseGame) game).setOtherBoard((BughouseGame) otherBoard); ((BughouseGame) otherBoard).setOtherBoard((BughouseGame) game); if (StringUtils.defaultIfEmpty( otherBoard.getHeader(PgnHeader.WhiteOnTop), "0") .equals("0")) { game.setHeader(PgnHeader.WhiteOnTop, "1"); } else { game.setHeader(PgnHeader.WhiteOnTop, "0"); } } } protected void adjustWhiteOnTopHeader(Game game, Style12Message message) { if (message.isWhiteOnTop) { // Respect the flip variable. game.setHeader(PgnHeader.WhiteOnTop, "1"); } else if (StringUtils.equalsIgnoreCase(message.whiteName, connector.userName)) { game.setHeader(PgnHeader.WhiteOnTop, "0"); } else if (StringUtils.equalsIgnoreCase(message.whiteName, connector.userFollowing)) { game.setHeader(PgnHeader.WhiteOnTop, "0"); } else if (StringUtils.equalsIgnoreCase(message.blackName, connector.userName)) { game.setHeader(PgnHeader.WhiteOnTop, "1"); } else if (StringUtils.equalsIgnoreCase(message.blackName, connector.userFollowing)) { game.setHeader(PgnHeader.WhiteOnTop, "1"); } else { game.setHeader(PgnHeader.WhiteOnTop, "0"); } } protected boolean isBughouse(Game game) { return game.getVariant() == Variant.bughouse || game.getVariant() == Variant.fischerRandomBughouse; } protected boolean isCrazyhouse(Game game) { return game.getVariant() == Variant.crazyhouse || game.getVariant() == Variant.fischerRandomCrazyhouse; } protected boolean observePartnerBoardForGame(Game game) { boolean result = false; // This lets you observe if you are simuled but obsing another game, // otherwise // it wont let you observe. if (connector.isSimulBugConnector()) { String white = IcsUtils .stripTitles(game.getHeader(PgnHeader.White)); String black = IcsUtils .stripTitles(game.getHeader(PgnHeader.Black)); if (StringUtils.equalsIgnoreCase(white, connector.getUserName()) || StringUtils.equalsIgnoreCase(white, connector .getSimulBugPartnerName()) || StringUtils.equalsIgnoreCase(black, connector .getUserName()) || StringUtils.equalsIgnoreCase(black, connector .getSimulBugPartnerName())) { return false; } } if (game.isInState(Game.PLAYING_STATE)) { result = connector.getPreferences().getBoolean( PreferenceKeys.BUGHOUSE_PLAYING_OPEN_PARTNER_BOARD); } else if (game.isInState(Game.OBSERVING_STATE)) { result = connector.getPreferences().getBoolean( PreferenceKeys.BUGHOUSE_OBSERVING_OPEN_PARTNER_BOARD); } return result; } /** * Parses and removes all of the game events from inboundEvent. Adjusts the * games in service. Returns a String with the game events removed. */ protected String parseGameEvents(String inboundMessage) { containedStyle12 = false; if (inboundMessage.length() > MAX_GAME_MESSAGE) { return inboundMessage; } else { if (LOG.isDebugEnabled()) { LOG.debug("Raw message in: " + inboundMessage); } boolean trimAtEnd = false; StringBuilder result = new StringBuilder(inboundMessage.length()); RaptorStringTokenizer tok = new RaptorStringTokenizer( inboundMessage, "\n"); while (tok.hasMoreTokens()) { String line = tok.nextToken(); if (LOG.isDebugEnabled()) { LOG.debug("Processing raw line: " + line); } G1Message g1Message = g1Parser.parse(line); if (g1Message != null) { process(g1Message, connector.getGameService()); trimAtEnd = true; continue; } Style12Message style12Message = style12Parser.parse(line); if (style12Message != null) { process(style12Message, connector.getGameService(), inboundMessage); containedStyle12 = true; continue; } B1Message b1Message = b1Parser.parse(line); if (b1Message != null) { process(b1Message, connector.getGameService()); continue; } GameEndMessage gameEndMessage = gameEndParser.parse(line); if (gameEndMessage != null) { process(gameEndMessage, connector.getGameService()); result.append(line + (tok.hasMoreTokens() ? "\n" : "")); trimAtEnd = true; continue; } IllegalMoveMessage illegalMoveMessage = illegalMoveParser .parse(line); if (illegalMoveMessage != null) { process(illegalMoveMessage, connector.getGameService()); result.append(line + (tok.hasMoreTokens() ? "\n" : "")); continue; } RemovingObsGameMessage removingObsGameMessage = removingObsGameParser .parse(line); if (removingObsGameMessage != null) { process(removingObsGameMessage, inboundMessage, connector .getGameService()); result.append(line + (tok.hasMoreTokens() ? "\n" : "")); continue; } if (processPendInfo(line)) { trimAtEnd = true; continue; } NoLongerExaminingGameMessage noLonerExaminingGameMessage = noLongerExaminingParser .parse(line); if (noLonerExaminingGameMessage != null) { process(noLonerExaminingGameMessage, connector .getGameService()); result.append(line + (tok.hasMoreTokens() ? "\n" : "")); continue; } takebackParser.parse(line); ChatEvent followingEvent = followingParser.parse(line); if (followingEvent != null && followingEvent.getType() == ChatType.FOLLOWING) { connector.setUserFollowing(followingEvent.getSource()); // Don't eat this line. Let it be appended so the event gets // published. // It is just being used here to set the user we are // following so white on top // can be set properly. } if (line.startsWith("Entering setup mode.") && !inboundMessage.contains("<12>")) { processExaminedGameBecameSetup(); } result.append(line + (tok.hasMoreTokens() ? "\n" : "")); } return trimAtEnd ? result.toString().trim() : result.toString(); } } /** * Parses out the Moves message from inboundEvent. It is assumed moves * messages will never contain other messages. * * @param inboundEvent * The inbound message. * @param events * The chatEvents */ protected String parseMovesMessage(String inboundMessage, List<ChatEvent> events) { MovesMessage movesMessage = movesParser.parse(inboundMessage); if (movesMessage != null) { process(movesMessage, connector.getGameService()); events.add(new ChatEvent(null, ChatType.MOVES, inboundMessage)); return null; } else { return inboundMessage; } } protected void process(B1Message message, GameService service) { if (LOG.isDebugEnabled()) { LOG.debug("Processing b1: " + message); } Game game = service.getGame(message.gameId); if (game == null) { if (exaimineGamesWaitingOnMoves.containsKey(message.gameId)) { exaimineB1sWaitingOnMoves.put(message.gameId, message); } else { if (LOG.isInfoEnabled()) { LOG .info("Received B1 for a game not in the GameService. " + "You could be ignoring a bug or zh game and get this."); } } } else { if (isBicsParser && isCrazyhouse(game) && !containedStyle12) { // See the documentation on the variable for an explanation of // why this is done. return; } updateGameForB1(game, message); service.fireDroppablePiecesChanged(message.gameId); } } protected void process(G1Message message, GameService service) { unprocessedG1Messages.put(message.gameId, message); } protected void process(GameEndMessage message, GameService service) { Game game = service.getGame(message.gameId); if (game == null) { // Bug game other boards might not be in the game service. // So no need to send a connector.onError. } else { switch (message.type) { case GameEndMessage.ABORTED: case GameEndMessage.ADJOURNED: case GameEndMessage.UNDETERMINED: game.setHeader(PgnHeader.Result, Result.UNDETERMINED .getDescription()); break; case GameEndMessage.BLACK_WON: game.setHeader(PgnHeader.Result, Result.BLACK_WON .getDescription()); break; case GameEndMessage.WHITE_WON: game.setHeader(PgnHeader.Result, Result.WHITE_WON .getDescription()); break; case GameEndMessage.DRAW: game.setHeader(PgnHeader.Result, Result.DRAW.getDescription()); break; default: LOG.error("Undetermined game end type. " + message); break; } game.setHeader(PgnHeader.ResultDescription, message.description); game.setHeader(PgnHeader.PlyCount, "" + game.getHalfMoveCount()); game.clearState(Game.ACTIVE_STATE | Game.IS_CLOCK_TICKING_STATE); game.addState(Game.INACTIVE_STATE); service.fireGameInactive(game.getId()); service.removeGame(game); takebackParser.clearTakebackMessages(game.getId()); } if (LOG.isDebugEnabled()) { LOG.debug("Processed game end: " + message); } } protected void process(IllegalMoveMessage message, GameService service) { // Except for simuls you can only place one game at a time. // For now ignore simuls and just send this to the first active game // found in the game service. Game[] allActive = service.getAllActiveGames(); for (Game game : allActive) { service.fireIllegalMove(game.getId(), message.move); } if (LOG.isDebugEnabled()) { LOG.debug("Processed illegal move: " + message); } } protected void process(MovesMessage message, GameService service) { if (LOG.isDebugEnabled()) { LOG.debug("Processing movesMessage: " + message); } Game game = service.getGame(message.gameId); if (game == null) { // Check to see if this was for a newly examined game. Style12Message style12 = exaimineGamesWaitingOnMoves .get(message.gameId); if (style12 != null) { exaimineGamesWaitingOnMoves.remove(message.gameId); game = IcsUtils.createExaminedGame(style12, message); B1Message b1Message = exaimineB1sWaitingOnMoves.get(game .getId()); if (b1Message != null) { updateGameForB1(game, b1Message); exaimineB1sWaitingOnMoves.remove(game.getId()); } service.addGame(game); // Respect the flip variable if its set. game.setHeader(PgnHeader.WhiteOnTop, style12.isWhiteOnTop ? "1" : "0"); service.fireGameCreated(game.getId()); if (LOG.isDebugEnabled()) { LOG.debug("Firing game created."); } } else { LOG .warn("Received a MovesMessage for a game not being managed. This can occur if the user manually types in the moves command. " + message.gameId); } } else { Style12Message style12 = exaimineGamesWaitingOnMoves .get(message.gameId); if (style12 != null) { // Both observed games becoming examined games and // setup games becoming examined games will flow through here. // Distinguishes between setup and observed. boolean isSetup = game.isInState(Game.SETUP_STATE); exaimineGamesWaitingOnMoves.remove(message.gameId); game = IcsUtils.createExaminedGame(style12, message); B1Message b1Message = exaimineB1sWaitingOnMoves.get(game .getId()); if (b1Message != null) { updateGameForB1(game, b1Message); exaimineB1sWaitingOnMoves.remove(game.getId()); } service.addGame(game); // Respect the flip variable if its set. game.setHeader(PgnHeader.WhiteOnTop, style12.isWhiteOnTop ? "1" : "0"); if (isSetup) { if (LOG.isDebugEnabled()) { LOG.debug("Firing fireSetupGameBecameExamined."); } service.fireSetupGameBecameExamined(game.getId()); } else { if (LOG.isDebugEnabled()) { LOG.debug("Firing fireObservedGameBecameExamined."); } // Need a delay for puzzlebot sometimes it opens too fast. try { Thread.sleep(250); } catch (InterruptedException ie) { } service.fireObservedGameBecameExamined(game.getId()); } } else { IcsUtils.updateGamesMoves(game, message); service.fireGameMovesAdded(game.getId()); } } } protected void process(NoLongerExaminingGameMessage message, GameService service) { Game game = service.getGame(message.gameId); if (game == null) { connector.onError( "Received no longer examining game message for a game not in the GameService. " + message, new Exception()); } else { game.setHeader(PgnHeader.ResultDescription, "Interrupted by unexamine."); game.setHeader(PgnHeader.Result, Result.UNDETERMINED .getDescription()); game.clearState(Game.ACTIVE_STATE | Game.IS_CLOCK_TICKING_STATE); game.addState(Game.INACTIVE_STATE); service.fireGameInactive(game.getId()); service.removeGame(game); takebackParser.clearTakebackMessages(game.getId()); } if (LOG.isDebugEnabled()) { LOG.debug("Processed no longer examining game message: " + message); } } protected void process(RemovingObsGameMessage message, String entireMessage, GameService service) { Game game = service.getGame(message.gameId); if (game == null) { if (LOG.isDebugEnabled()) { LOG .debug("Received removing obs game message for a game not in the GameService." + message); } } else { if (!entireMessage.contains("has made you an examiner of game ")) { game.setHeader(PgnHeader.ResultDescription, "Interrupted by unobserve"); game.setHeader(PgnHeader.Result, Result.UNDETERMINED .getDescription()); game .clearState(Game.ACTIVE_STATE | Game.IS_CLOCK_TICKING_STATE); game.addState(Game.INACTIVE_STATE); service.fireGameInactive(game.getId()); service.removeGame(game); takebackParser.clearTakebackMessages(game.getId()); } } if (LOG.isDebugEnabled()) { LOG.debug("Processed removing obs game: " + message); } } protected void process(Style12Message message, GameService service, String entireMessage) { if (LOG.isDebugEnabled()) { LOG.debug("Processing style 12: " + message); } long startTime = System.currentTimeMillis(); Game game = service.getGame(message.gameId); if (game != null) { if (game.isInState(Game.SETUP_STATE)) { processStyle12SetupAdjustment(game, message, service, entireMessage); } else { processStyle12Adjustment(game, message, service, entireMessage); } } else { G1Message g1Message = unprocessedG1Messages.get(message.gameId); if (g1Message == null) { processStyle12Creation(message, service, entireMessage); } else { processG1Creation(g1Message, message, service, entireMessage); } } if (LOG.isDebugEnabled()) { LOG.debug("Processed style 12: " + message + " in " + (System.currentTimeMillis() - startTime)); } } protected ChatEvent processBugWho(String message) { ChatEvent result = null; // Bics bugwho is different. Someone needs to write bics bugwho to get // it working. if (bugWhoUParser != null) { Bugger[] buggers = bugWhoUParser.parse(message); if (buggers == null) { Partnership[] partnerships = bugWhoPParser.parse(message); if (partnerships == null) { raptor.chat.BugGame[] bugGames = bugWhoGParser .parse(message); if (bugGames != null) { connector.getBughouseService().setGamesInProgress( bugGames); result = new ChatEvent(null, ChatType.BUGWHO_GAMES, message); } } else { connector.getBughouseService().setAvailablePartnerships( partnerships); result = new ChatEvent(null, ChatType.BUGWHO_AVAILABLE_TEAMS, message); } } else { connector.getBughouseService().setUnpartneredBuggers(buggers); result = new ChatEvent(null, ChatType.BUGWHO_UNPARTNERED_BUGGERS, message); } } return result; } /** * Observed/Playing games starts flow here (i.e. All games that contain a G1 * message) */ protected void processG1Creation(G1Message g1Message, Style12Message message, GameService service, String entireMessage) { if (LOG.isDebugEnabled()) { LOG.debug("Processing new obs/playing game."); } unprocessedG1Messages.remove(message.gameId); Game game = IcsUtils.createGame(g1Message, message, isBicsParser); IcsUtils.updateNonPositionFields(game, message); IcsUtils.updatePosition(game, message); IcsUtils.verifyLegal(game); if (game instanceof FischerRandomGame) { ((FischerRandomGame) game).initialPositionIsSet(); } else if (game instanceof FischerRandomCrazyhouseGame) { ((FischerRandomCrazyhouseGame) game).initialPositionIsSet(); } else if (game instanceof FischerRandomBughouseGame) { ((FischerRandomBughouseGame) game).initialPositionIsSet(); } if (game.getVariant() == Variant.wild || game.getVariant() == Variant.fischerRandom) { game.setHeader(PgnHeader.FEN, game.toFen()); } service.addGame(game); adjustWhiteOnTopHeader(game, message); if (isBughouse(game)) { /** * BICS does'nt have the partner game id in the G1 so you have to * handle BICS and FICS differently. */ if (g1Message.parterGameId.equals("0")) { adjustBughouseHeadersAndFollowPartnersGamesForBics(game, message, service); } else { adjustBughouseHeadersAndFollowPartnersGamesForFics(game, g1Message, message, service); } } if (LOG.isDebugEnabled()) { LOG.debug("Firing game created."); } service.fireGameCreated(game.getId()); /** * Send a request for the moves. */ if (message.fullMoveNumber > 1 || message.fullMoveNumber == 1 && !message.isWhitesMoveAfterMoveIsMade) { connector.sendMessage("moves " + message.gameId, true, ChatType.MOVES); } } /** * Handles the fics pendinfo messages. * * @param line * THe line being parsed. * @return True if it was a pendinfo message and was processed, false * otherwise. */ protected boolean processPendInfo(String line) { if (line.startsWith("<pf>")) { System.err.println(line); RaptorStringTokenizer tok = new RaptorStringTokenizer(line, " =", true); Offer offer = new Offer(); offer.setReceiving(true); tok.nextToken(); offer.setId(tok.nextToken()); tok.nextToken(); offer.setSource(tok.nextToken()); tok.nextToken(); String type = tok.nextToken(); if (type.equals("partner")) { offer.setType(OfferType.partner); offer.setDeclineCommand("decline " + offer.getId()); offer.setDeclinable(true); offer.setDeclineAllCommand("decline t all"); offer.setCommand("accept " + offer.getId()); offer.setDescription("Accept partnership offer from " + offer.getSource()); offer.setDeclineDescription("Decline partnership offer from " + offer.getSource()); } else if (type.equals("match")) { offer.setType(OfferType.match); offer.setCommand("accept " + offer.getId()); offer.setDeclinable(true); offer.setDeclineCommand("decline " + offer.getId()); offer.setDeclineAllCommand("decline t all"); tok.nextToken(); String challengeDescription = tok.getWhatsLeft(); offer.setDeclineDescription("Decline challenge " + challengeDescription); offer .setDescription("Accept challenge " + challengeDescription); } else if (type.equals("draw")) { offer.setType(OfferType.draw); offer.setCommand("accept " + offer.getId()); offer.setDeclinable(true); offer.setDeclineCommand("decline " + offer.getId()); offer.setDeclineAllCommand("decline t all"); offer.setDeclineDescription("Decline draw offer from " + offer.getSource()); offer.setDescription("Accept draw offer from " + offer.getSource()); } else if (type.equals("adjourn")) { offer.setType(OfferType.adjourn); offer.setCommand("accept " + offer.getId()); offer.setDeclinable(true); offer.setDeclineCommand("decline " + offer.getId()); offer.setDeclineAllCommand("decline t all"); offer.setDescription("Accept adjourn offer from " + offer.getSource()); offer.setDeclineDescription("Decline adjourn offer from " + offer.getSource()); } else if (type.equals("abort")) { offer.setType(OfferType.abort); offer.setCommand("accept " + offer.getId()); offer.setDeclinable(true); offer.setDeclineCommand("decline " + offer.getId()); offer.setDeclineAllCommand("decline t all"); offer.setDescription("Accept abort offer from " + offer.getSource()); offer.setDeclineDescription("Decline abort offer from " + offer.getSource()); } else if (type.equals("takeback")) { offer.setType(OfferType.takeback); offer.setCommand("accept " + offer.getId()); offer.setDeclinable(true); offer.setDeclineCommand("decline " + offer.getId()); offer.setDeclineAllCommand("decline t all"); tok.nextToken(); String taokebackMoves = tok.getWhatsLeft(); offer.setDescription("Accept takeback " + taokebackMoves + " halfmoves offer from " + offer.getSource()); offer.setDeclineDescription("Decline takeback " + taokebackMoves + " halfmoves offer from " + offer.getSource()); } else { return true; } connector.getGameService().fireOfferReceived(offer); return true; } else if (line.startsWith("<pt>")) { System.err.println(line); RaptorStringTokenizer tok = new RaptorStringTokenizer(line, " =", true); Offer offer = new Offer(); offer.setReceiving(false); tok.nextToken(); offer.setId(tok.nextToken()); tok.nextToken(); offer.setSource(tok.nextToken()); tok.nextToken(); String type = tok.nextToken(); if (type.equals("partner")) { offer.setType(OfferType.partner); offer.setCommand("withdraw " + offer.getId()); offer.setDescription("Withdraw partnership offer to " + offer.getSource()); } else if (type.equals("match")) { offer.setType(OfferType.match); offer.setCommand("withdraw " + offer.getId()); tok.nextToken(); offer .setDescription("Withdraw challenge " + tok.getWhatsLeft()); } else if (type.equals("draw")) { offer.setType(OfferType.draw); offer.setCommand("withdraw " + offer.getId()); offer.setDescription("Withdraw draw offer to " + offer.getSource()); } else if (type.equals("adjourn")) { offer.setType(OfferType.adjourn); offer.setCommand("withdraw " + offer.getId()); offer.setDescription("Withdraw adjourn offer to " + offer.getSource()); } else if (type.equals("abort")) { offer.setType(OfferType.abort); offer.setCommand("withdraw " + offer.getId()); offer.setDescription("Withdraw abort offer to " + offer.getSource()); } else if (type.equals("takeback")) { offer.setType(OfferType.takeback); offer.setCommand("withdraw " + offer.getId()); tok.nextToken(); offer.setDescription("Withdraw takeback " + tok.getWhatsLeft() + " halfmoves offer to " + offer.getSource()); } else { return true; } connector.getGameService().fireOfferReceived(offer); return true; } else if (line.startsWith("<pr>")) { System.err.println(line); RaptorStringTokenizer tok = new RaptorStringTokenizer(line, " =", true); tok.nextToken(); connector.getGameService().fireOfferRemoved(tok.nextToken()); return true; } return false; } protected ChatEvent processSought(String message) { ChatEvent result = null; if (soughtParser != null) { Seek[] seeks = soughtParser.parse(message); if (seeks != null) { connector.getSeekService().setSeeks(seeks); result = new ChatEvent(null, ChatType.SEEKS, message); } } return result; } /** * Playing,Observing,Examining style 12 adjustments flow through here. */ protected void processStyle12Adjustment(Game game, Style12Message message, GameService service, String entireMessage) { if (LOG.isDebugEnabled()) { LOG.debug("Processing obs/playing/ex position move."); } if (entireMessage.contains("- entering examine mode.")) { if (LOG.isDebugEnabled()) { LOG.debug("Handling bsetup to examine mode transition."); } // Handles one case of the transition from bsetup mode to examine // mode. Game examineGame = IcsUtils.createGame(message, entireMessage); if (message.relation == Style12Message.EXAMINING_GAME_RELATION && !examineGame.isInState(Game.SETUP_STATE)) { exaimineGamesWaitingOnMoves.put(game.getId(), message); connector.sendMessage("moves " + message.gameId, true, ChatType.MOVES); } } else if (game.isInState(Game.OBSERVING_EXAMINED_STATE) && message.relation == Style12Message.EXAMINING_GAME_RELATION) { if (LOG.isDebugEnabled()) { LOG.debug("Handling observer became examiner transition."); } // Handles a user becoming an examiner of a game he/she was // observing. exaimineGamesWaitingOnMoves.put(game.getId(), message); connector.sendMessage("moves " + message.gameId, true, ChatType.MOVES); } else if (game.isInState(Game.EXAMINING_STATE) && entireMessage.contains("Entering setup mode.\n")) { if (LOG.isDebugEnabled()) { LOG .debug("Handling examined game became setup game transition."); } // Handles an examined game becoming a setup game. game = IcsUtils.createGame(message, entireMessage); service.addGame(game); service.fireExaminedGameBecameSetup(game.getId()); } else { // No game state transition occured. if (LOG.isDebugEnabled()) { LOG .debug("No state transitions occured. Processing style12 on existing game."); } // Takebacks may have effected the state of the game so first // adjsut to those. // adjust takebacks will also do nothing on refreshes and end // games // but will return true. if (!IcsUtils.adjustToTakebacks(game, message, connector)) { if (LOG.isDebugEnabled()) { LOG.debug("Making move in obs/playing position."); } // Now add the move to the game. // Game Ends and Refreshes dont involve adding a move. if (IcsUtils.addCurrentMove(game, message)) { if (LOG.isDebugEnabled()) { LOG.debug("Position was a move firing state changed."); } service.fireGameStateChanged(message.gameId, true); } else { // I'm not sure this block of code is ever hit // anymore. // TO DO: look at removing it. if (LOG.isDebugEnabled()) { LOG .debug("Position was not a move firing state changed."); } service.fireGameStateChanged(message.gameId, false); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Adjusted for takebacks."); } service.fireGameStateChanged(message.gameId, false); } } } /** * Examined/Bsetup/Isolated Positions game starts flow through here (i.e. * All games that didnt have a G1 message) */ protected void processStyle12Creation(Style12Message message, GameService service, String entireMessage) { if (LOG.isDebugEnabled()) { LOG.debug("Processing new ex or bsetup game."); } if (message.relation == Style12Message.OBSERVING_EXAMINED_GAME_RELATION || message.relation == Style12Message.OBSERVING_GAME_RELATION) { // This is probably from a game that was vetoed because the user was // playing. // Just return the unobserve has'nt taken effect yet. if (LOG.isInfoEnabled()) { LOG .info("A style 12 message was received for an observed game " + "that wasnt being managed. Assuming this was because you " + "are playing a game and have the ignore observed games if playing " + "preference enabled."); } return; } Game game = IcsUtils.createGame(message, entireMessage); if (message.relation == Style12Message.EXAMINING_GAME_RELATION && !game.isInState(Game.SETUP_STATE)) { exaimineGamesWaitingOnMoves.put(game.getId(), message); connector.sendMessage("moves " + message.gameId, true, ChatType.MOVES); } else { service.addGame(game); // Respect the flip variable if its set. game.setHeader(PgnHeader.WhiteOnTop, message.isWhiteOnTop ? "1" : "0"); service.fireGameCreated(game.getId()); if (LOG.isDebugEnabled()) { LOG.debug("Firing game created."); } } } /** * Setup style 12 adjustments flow through here. */ protected void processStyle12SetupAdjustment(Game game, Style12Message message, GameService service, String entireMessage) { // Examined/BSetup/obs ex moves flow through here. if (LOG.isDebugEnabled()) { LOG.debug("Processing bsetup or examine position move."); } if (entireMessage .contains("Game is validated - entering examine mode.\n")) { // Add this game to the games waiting on moves. // Send a moves message. // Transition from BSETUP to EXAMINE when moves arrives. exaimineGamesWaitingOnMoves.put(game.getId(), message); connector.sendMessage("moves " + message.gameId, true, ChatType.MOVES); } else { // Clear out the game and start over. // There is no telling what happened // in a setup or examine game. IcsUtils.resetGame(game, message); service.fireGameStateChanged(message.gameId, true); } } protected void updateGameForB1(Game game, B1Message message) { if (isBughouse(game) && (game.isInState(Game.EXAMINING_STATE) || game .isInState(Game.OBSERVING_EXAMINED_STATE))) { // On Fics when examining a bug game you don't get pieces. // To handle all the issues around that just set 1 of everything. game.setDropCount(WHITE, PAWN, 1); game.setDropCount(WHITE, QUEEN, 1); game.setDropCount(WHITE, ROOK, 1); game.setDropCount(WHITE, KNIGHT, 1); game.setDropCount(WHITE, BISHOP, 1); game.setDropCount(BLACK, PAWN, 1); game.setDropCount(BLACK, QUEEN, 1); game.setDropCount(BLACK, ROOK, 1); game.setDropCount(BLACK, KNIGHT, 1); game.setDropCount(BLACK, BISHOP, 1); } else { for (int i = 1; i < message.whiteHoldings.length; i++) { game.setDropCount(WHITE, i, message.whiteHoldings[i]); } for (int i = 1; i < message.blackHoldings.length; i++) { game.setDropCount(BLACK, i, message.blackHoldings[i]); } } } }
package com.lukekorth.android_500px; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.preference.ListPreference; import android.preference.MultiSelectListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceCategory; import android.text.TextUtils; import android.text.format.DateUtils; import com.fivehundredpx.api.auth.AccessToken; import com.fivehundredpx.api.auth.FiveHundredPxOAuthActivity; import com.lukekorth.android_500px.helpers.LogReporting; import com.lukekorth.android_500px.helpers.Settings; import com.lukekorth.android_500px.helpers.Utils; import com.lukekorth.android_500px.models.Photos; import com.lukekorth.android_500px.models.User; import com.lukekorth.android_500px.models.UserUpdatedEvent; import com.lukekorth.android_500px.models.WallpaperChangedEvent; import com.lukekorth.android_500px.services.ApiService; import com.lukekorth.android_500px.services.WallpaperService; import com.squareup.otto.Subscribe; import com.squareup.picasso.Picasso; import com.squareup.picasso.Target; import java.util.Set; import fr.nicolaspomepuy.discreetapprate.AppRate; import fr.nicolaspomepuy.discreetapprate.RetryPolicy; public class SettingsActivity extends PreferenceActivity implements Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener { private static final int FIVE_HUNDRED_PX_LOGIN = 20; private Preference mLogin; private ListPreference mFeature; private MultiSelectListPreference mCategories; private ListPreference mInterval; private Preference mCurrentPhoto; private Preference mNextPhoto; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.layout.settings); mCurrentPhoto = findPreference("current_photo"); mNextPhoto = findPreference("next_photo"); mLogin = findPreference("login"); mFeature = (ListPreference) findPreference("feature"); mCategories = (MultiSelectListPreference) findPreference("categories"); mInterval = (ListPreference) findPreference("update_interval"); mNextPhoto.setOnPreferenceClickListener(this); mCurrentPhoto.setOnPreferenceClickListener(this); mLogin.setOnPreferenceClickListener(this); findPreference("contact").setOnPreferenceClickListener(this); mFeature.setOnPreferenceChangeListener(this); mCategories.setOnPreferenceChangeListener(this); mInterval.setOnPreferenceChangeListener(this); findPreference("enable").setOnPreferenceChangeListener(this); findPreference("use_only_wifi").setOnPreferenceChangeListener(this); findPreference("allow_nsfw").setOnPreferenceChangeListener(this); setFeatureSummary(mFeature.getValue()); setCategoriesSummary(mCategories.getValues()); setIntervalSummary(mInterval.getValue()); findPreference("version").setSummary(BuildConfig.VERSION_NAME); if (Utils.supportsParallax(this)) { findPreference("use_parallax").setOnPreferenceChangeListener(this); } else { ((PreferenceCategory) findPreference("settings")) .removePreference(findPreference("use_parallax")); } WallpaperApplication.getBus().register(this); onUserUpdated(null); runApiService(); AppRate.with(this) .text(R.string.rate_app) .initialLaunchCount(3) .retryPolicy(RetryPolicy.EXPONENTIAL) .checkAndShow(); } @Override protected void onResume() { super.onResume(); onWallpaperChanged(null); if (Utils.shouldUpdateWallpaper(this)) { runWallpaperService(); } } @Override protected void onDestroy() { WallpaperApplication.getBus().unregister(this); super.onDestroy(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == FIVE_HUNDRED_PX_LOGIN) { if (resultCode == Activity.RESULT_OK) { User.newUser(this, (AccessToken) data.getParcelableExtra(FiveHundredPxOAuthActivity.ACCESS_TOKEN)); } else if (resultCode != Activity.RESULT_CANCELED) { new AlertDialog.Builder(this) .setTitle(R.string.login_error) .setMessage(R.string.login_error_message) .setPositiveButton(android.R.string.ok, null) .show(); } } } @Subscribe public void onUserUpdated(UserUpdatedEvent event) { User user = User.getUser(); if (user != null) { mLogin.setTitle(user.userName); mLogin.setSummary(getString(R.string.click_to_logout)); WallpaperApplication.getPicasso(this) .load(user.photo) .error(android.R.drawable.stat_notify_error) .into(mUserImageCallback); } else { mLogin.setTitle(R.string.login_with_500px); mLogin.setSummary(R.string.login_with_500px_summary); mLogin.setIcon(null); } } private Target mUserImageCallback = new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { mLogin.setIcon(new BitmapDrawable(bitmap)); } @Override public void onBitmapFailed(Drawable errorDrawable) { } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { } }; @Subscribe public void onWallpaperChanged(WallpaperChangedEvent event) { Photos photo = Photos.getCurrentPhoto(); if (photo != null) { CharSequence timeSet = DateUtils.getRelativeTimeSpanString(photo.seenAt, System.currentTimeMillis(), 0); mCurrentPhoto.setTitle(photo.name); mCurrentPhoto.setSummary("© " + photo.userName + " / 500px\n" + getString(R.string.set) + " " + timeSet); WallpaperApplication.getPicasso(this) .load(photo.imageUrl) .error(android.R.drawable.stat_notify_error) .into(mCurrentImageCallback); } else { mCurrentPhoto.setTitle(R.string.no_current_photo); } if (Settings.isEnabled(this)) { int photosRemaining = Photos.unseenPhotoCount(this); if (photosRemaining > 0) { mNextPhoto.setEnabled(true); long nextPhotoTime = Settings.getLastUpdated(this) + (Settings.getUpdateInterval(this) * 1000); if (nextPhotoTime + 59000 < System.currentTimeMillis()) { mNextPhoto.setTitle(getString(R.string.next_photo) + " " + getString(R.string.next_unlock)); } else { CharSequence nextTime = DateUtils.getRelativeTimeSpanString(nextPhotoTime, System.currentTimeMillis(), 0); mNextPhoto.setTitle(getString(R.string.next_photo) + " " + nextTime); } mNextPhoto.setSummary(photosRemaining + " " + getString(R.string.remaining_photos)); } else { mNextPhoto.setEnabled(false); mNextPhoto.setTitle(R.string.no_photos_remaining); mNextPhoto.setSummary(R.string.select_different_feature_or_categories); } } else { mNextPhoto.setTitle(R.string.disabled); mNextPhoto.setSummary(R.string.enable_below); } } private Target mCurrentImageCallback = new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { mCurrentPhoto.setIcon(new BitmapDrawable(bitmap)); } @Override public void onBitmapFailed(Drawable errorDrawable) { } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { } }; @Override public boolean onPreferenceClick(Preference preference) { if (preference.getKey().equals(mCurrentPhoto.getKey())) { startActivity(new Intent(this, HistoryActivity.class)); return true; } else if (preference.getKey().equals(mNextPhoto.getKey())) { mNextPhoto.setTitle(R.string.loading); mNextPhoto.setSummary(""); runWallpaperService(); return true; } else if (preference.getKey().equals("login")) { if (User.isUserLoggedIn()) { User.logout(); WallpaperApplication.getBus().post(new UserUpdatedEvent()); } else { Intent intent = new Intent(this, FiveHundredPxOAuthActivity.class) .putExtra(FiveHundredPxOAuthActivity.CONSUMER_KEY, BuildConfig.CONSUMER_KEY) .putExtra(FiveHundredPxOAuthActivity.CONSUMER_SECRET, BuildConfig.CONSUMER_SECRET); startActivityForResult(intent, FIVE_HUNDRED_PX_LOGIN); } } else if (preference.getKey().equals("contact")) { new LogReporting(this).collectAndSendLogs(); return true; } return false; } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String key = preference.getKey(); if (key.equals(mFeature.getKey())) { setFeatureSummary((String) newValue); } else if (key.equals(mCategories.getKey())) { setCategoriesSummary((Set<String>) newValue); } else if (key.equals(mInterval.getKey())) { Settings.setUpdateInterval(this, (String) newValue); setIntervalSummary((String) newValue); onWallpaperChanged(null); } else if (key.equals("use_parallax")) { Settings.setDesiredWidth(this, 0); } runApiService(); return true; } private void runApiService() { startService(new Intent(this, ApiService.class)); } private void runWallpaperService() { startService(new Intent(this, WallpaperService.class)); } private void setFeatureSummary(String index) { String summary = getSummary(R.array.feature_index, R.array.features, index); if (TextUtils.isEmpty(summary)) { summary = getString(R.string.popular); } mFeature.setSummary(summary); } private void setCategoriesSummary(Set<String> indexes) { if (indexes.size() == 0) { mCategories.setSummary(getString(R.string.landscapes)); } else { String[] valueArray = getResources().getStringArray(R.array.categories); String summary = ""; for (String index : indexes) { summary += valueArray[Integer.parseInt(index)] + ", "; } mCategories.setSummary(summary.substring(0, summary.length() - 2)); } } private void setIntervalSummary(String index) { String summary = getSummary(R.array.interval_index, R.array.intervals, index); if (TextUtils.isEmpty(summary)) { summary = getString(R.string.one_hour); } mInterval.setSummary(summary); } private String getSummary(int indexArrayId, int valueArrayId, String index) { String[] indexArray = getResources().getStringArray(indexArrayId); String[] valueArray = getResources().getStringArray(valueArrayId); int i; for (i = 0; i < indexArray.length; i++) { if (indexArray[i].equals(index)) { return valueArray[i]; } } return ""; } }
package core; import org.junit.Test; import java.util.*; import static org.junit.Assert.*; public class GraphReducerTest { /** * Create a node map with a given amount of nodes. * @param numNodes The number of nodes to create. * @return A node map with a given amount of nodes. */ private HashMap<Integer, Node> createNodeMap(int numNodes) { HashMap<Integer, Node> nodeMap = new HashMap<>(); for (int i = 1; i <= numNodes; i++) { nodeMap.put(i, new Node(i, "", i)); } return nodeMap; } /** * Test the determineParents method without any node having a parent. */ @Test public void testDetermineParentsEmpty() { HashMap<Integer, Node> nodeMap = new HashMap<>(); Node n1 = new Node(1, "A", 1); nodeMap.put(1, n1); GraphReducer.determineParents(nodeMap); assertTrue(nodeMap.get(1).getParents().size() == 0); } /** * Test the determineParents method with singular linked nodes. */ @Test public void testDetermineParentsLinkedParents() { HashMap<Integer, Node> nodeMap = new HashMap<>(); Node n1 = new Node(1, "A", 1); Node n2 = new Node(2, "B", 2); Node n3 = new Node(3, "C", 3); n1.addLink(2); n2.addLink(3); nodeMap.put(1, n1); nodeMap.put(2, n2); nodeMap.put(3, n3); GraphReducer.determineParents(nodeMap); assertTrue(nodeMap.get(1).getParents().size() == 0); assertTrue(nodeMap.get(2).getParents().size() == 1); assertTrue(nodeMap.get(3).getParents().size() == 1); assertTrue(nodeMap.get(2).getParents().get(0) == 1); assertTrue(nodeMap.get(3).getParents().get(0) == 2); } /** * Test the determineParents method. */ @Test public void testDetermineParentsDoubleParent() { HashMap<Integer, Node> nodeMap = new HashMap<>(); Node n1 = new Node(1, "A", 1); Node n2 = new Node(2, "B", 2); Node n3 = new Node(3, "C", 3); n1.addLink(3); n2.addLink(3); nodeMap.put(1, n1); nodeMap.put(2, n2); nodeMap.put(3, n3); GraphReducer.determineParents(nodeMap); assertTrue(nodeMap.get(1).getParents().size() == 0); assertTrue(nodeMap.get(2).getParents().size() == 0); assertTrue(nodeMap.get(3).getParents().size() == 2); assertTrue(nodeMap.get(3).getParents().get(0) == 1); assertTrue(nodeMap.get(3).getParents().get(1) == 2); } /** * Test the collapsing of a Node sequence of three nodes. */ @Test public void testCollapseNodeSequence() { HashMap<Integer, Node> nodeMap = createNodeMap(3); nodeMap.get(1).addLink(2); nodeMap.get(2).addLink(3); GraphReducer.determineParents(nodeMap); assertTrue(GraphReducer.collapseNodeSequence(nodeMap, nodeMap.get(1))); assertTrue(nodeMap.get(1).getLinks(nodeMap).size() == 1); assertTrue(nodeMap.get(1).getLinks(nodeMap).get(0) == nodeMap.get(3).getId()); assertNull(nodeMap.get(2)); assertTrue(nodeMap.get(3).getParents(nodeMap).size() == 1); assertTrue(nodeMap.get(3).getParents(nodeMap).get(0) == nodeMap.get(1).getId()); } /** * Test the collapsing of a parent with two children. */ @Test public void testCollapseBubble() { HashMap<Integer, Node> nodeMap = createNodeMap(6); nodeMap.get(1).setSequence("A"); nodeMap.get(1).setLinks(new ArrayList<>(Arrays.asList(2, 3))); nodeMap.get(2).setLinks(new ArrayList<>(Arrays.asList(4))); nodeMap.get(3).setLinks(new ArrayList<>(Arrays.asList(4))); nodeMap.get(4).setLinks(new ArrayList<>(Arrays.asList(5, 6))); // Collapse the bubble GraphReducer.determineParents(nodeMap); assertTrue(GraphReducer.collapseBubble(nodeMap, nodeMap.get(1))); assertEquals(2, nodeMap.get(1).getLinks(nodeMap).size()); assertEquals(5, (int) nodeMap.get(1).getLinks(nodeMap).get(0)); assertEquals(6, (int) nodeMap.get(1).getLinks(nodeMap).get(1)); assertEquals(1, nodeMap.get(1).getCollapseLevel()); assertEquals(NodeType.BUBBLE, nodeMap.get(1).getType()); assertEquals("", nodeMap.get(1).getSequence()); assertNull(nodeMap.get(2)); assertNull(nodeMap.get(3)); assertNull(nodeMap.get(4)); } /** * Test that bubbles in which the grandchild has more parents than the parent has children * should not be collapsed. */ @Test public void testBubbleShouldNotCollapse() { HashMap<Integer, Node> nodeMap = createNodeMap(6); nodeMap.get(1).setLinks(new ArrayList<>(Arrays.asList(2, 6))); nodeMap.get(2).setLinks(new ArrayList<>(Arrays.asList(3, 4))); nodeMap.get(3).setLinks(new ArrayList<>(Arrays.asList(5))); nodeMap.get(4).setLinks(new ArrayList<>(Arrays.asList(5))); nodeMap.get(6).setLinks(new ArrayList<>(Arrays.asList(5))); // Collapse the bubble GraphReducer.determineParents(nodeMap); assertFalse(GraphReducer.collapseBubble(nodeMap, nodeMap.get(2))); assertNotNull(nodeMap.get(3)); assertNotNull(nodeMap.get(4)); assertNotNull(nodeMap.get(5)); assertEquals(1, nodeMap.get(6).getLinks(nodeMap).size()); } /** * Test whether the counter for the number of lower collapses is working correctly * when the bubble contains a collapsed bubble at a child of the parent in the bubble. */ @Test public void testBubbleCollapseCounter() { List<NodeType> types = new ArrayList<>(Arrays.asList(NodeType.BUBBLE, NodeType.INDEL)); for (NodeType type : types) { for (int i = 2; i <= 4; i++) { HashMap<Integer, Node> nodeMap = createNodeMap(4); nodeMap.get(2).setType(type); nodeMap.get(i).incrementCollapseLevel(); nodeMap.get(1).setLinks(new ArrayList<>(Arrays.asList(2, 3))); nodeMap.get(2).setLinks(new ArrayList<>(Arrays.asList(4))); nodeMap.get(3).setLinks(new ArrayList<>(Arrays.asList(4))); assertEquals(0, nodeMap.get(1).getCollapseLevel()); assertEquals(1, nodeMap.get(i).getCollapseLevel()); // Collapse the bubble GraphReducer.determineParents(nodeMap); assertTrue(GraphReducer.collapseBubble(nodeMap, nodeMap.get(1))); assertEquals(2, nodeMap.get(1).getCollapseLevel()); } } } /** * Test the collapsing of a triangle of nodes. */ @Test public void testCollapseIndel() { HashMap<Integer, Node> nodeMap = createNodeMap(5); nodeMap.get(1).setSequence("A"); nodeMap.get(1).setLinks(new ArrayList<>(Arrays.asList(2, 3))); nodeMap.get(2).setLinks(new ArrayList<>(Arrays.asList(3))); nodeMap.get(3).setLinks(new ArrayList<>(Arrays.asList(4, 5))); // Collapse the indel GraphReducer.determineParents(nodeMap); assertTrue(GraphReducer.collapseIndel(nodeMap, nodeMap.get(1))); assertTrue(nodeMap.get(1).getLinks(nodeMap).size() == 2); assertTrue(nodeMap.get(1).getLinks(nodeMap).get(0) == 4); assertTrue(nodeMap.get(1).getLinks(nodeMap).get(1) == 5); assertEquals(1, nodeMap.get(1).getCollapseLevel()); assertEquals(NodeType.INDEL, nodeMap.get(1).getType()); assertEquals("", nodeMap.get(1).getSequence()); assertNull(nodeMap.get(2)); assertNull(nodeMap.get(3)); } /** * Test that indels in which the grandchild has more parents than the parent has children * should not be collapsed. */ @Test public void testIndelShouldNotCollapse() { HashMap<Integer, Node> nodeMap = createNodeMap(5); nodeMap.get(1).setLinks(new ArrayList<>(Arrays.asList(2, 3))); nodeMap.get(2).setLinks(new ArrayList<>(Arrays.asList(3, 4))); nodeMap.get(3).setLinks(new ArrayList<>(Arrays.asList(5))); // Collapse the bubble GraphReducer.determineParents(nodeMap); GraphReducer.collapseIndel(nodeMap, nodeMap.get(1)); assertNotNull(nodeMap.get(2)); assertNotNull(nodeMap.get(3)); assertEquals(1, nodeMap.get(4).getParents(nodeMap).size()); assertEquals(1, nodeMap.get(5).getParents(nodeMap).size()); } /** * Test whether the counter for the number of lower collapses is working correctly. */ @Test public void testIndelCollapseCounter() { List<NodeType> types = new ArrayList<>(Arrays.asList(NodeType.BUBBLE, NodeType.INDEL)); for (NodeType type : types) { for (int i = 2; i <= 3; i++) { HashMap<Integer, Node> nodeMap = createNodeMap(3); nodeMap.get(i).setType(type); nodeMap.get(i).incrementCollapseLevel(); nodeMap.get(1).setLinks(new ArrayList<>(Arrays.asList(2, 3))); nodeMap.get(2).setLinks(new ArrayList<>(Arrays.asList(3))); assertEquals(0, nodeMap.get(1).getCollapseLevel()); assertEquals(1, nodeMap.get(i).getCollapseLevel()); GraphReducer.determineParents(nodeMap); assertTrue(GraphReducer.collapseIndel(nodeMap, nodeMap.get(1))); assertEquals(2, nodeMap.get(1).getCollapseLevel()); } } } }
package tours; import org.junit.Test; import tours.compiler.CompilerTools; import java.io.IOException; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class TypeCheckerTest { @Test public void testVariableDeclarations() { assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/variable_declaration.tours"); } @Test public void testBooleanExpressions() { assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/boolean_expressions.tours"); } @Test public void testForStatement() { assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/statement_for.tours"); } @Test public void testWhileStatement() { assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/statement_while.tours"); } @Test public void testIfStatement() { assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/statement_if.tours"); } @Test public void testAssignments() { assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/assignments.tours"); assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/assignments_boolean.tours"); assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/assignments_character.tours"); assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/assignments_integer.tours"); assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/assignments_string.tours"); assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/assignments_array_boolean.tours"); assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/assignments_array_character.tours"); assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/assignments_array_integer.tours"); assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/assignments_array_string.tours"); assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/assignments_if_else.tours"); assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/assignments_compound.tours"); assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/array_length.tours"); } @Test public void testFunctions() { assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/functions_arguments_primitive_type.tours"); assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/functions_arguments_array_type.tours"); assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/functions_return_array_type.tours"); } @Test public void testInput() { assertEqualTypeCheckErrorList(Arrays.asList(), "src/test/java/tours/examples/typechecker/input.tours"); assertEqualTypeCheckErrorList(Arrays.asList( "Error <input not defined for array element> on line 3, pos 10", "Error <input not defined for array element> on line 4, pos 24" ), "src/test/java/tours/examples/typechecker/invalid/invalid_input.tours"); } @Test public void testInvalidPrint() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <print not defined for array element> on line 3, pos 10", "Error <print not defined for array element> on line 4, pos 24" ), "src/test/java/tours/examples/typechecker/invalid/invalid_print.tours"); } @Test public void testInvalidCompareExpressions() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <compare not implemented for strings> on line 2, pos 4", "Error <compare not implemented for arrays> on line 3, pos 4", "Error <compare not implemented for arrays> on line 4, pos 4", "Error <compare not implemented for arrays> on line 5, pos 4", "Error <compare not implemented for arrays> on line 6, pos 4", "Error <compare not implemented for strings> on line 8, pos 4", "Error <compare not implemented for arrays> on line 9, pos 4", "Error <compare not implemented for arrays> on line 10, pos 4", "Error <compare not implemented for arrays> on line 11, pos 4", "Error <compare not implemented for arrays> on line 12, pos 4" ), "src/test/java/tours/examples/typechecker/invalid/invalid_compare_expressions.tours"); } @Test public void testMismatchingTypesBasic() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <mismatching types> on line 2, pos 14", "Error <mismatching types> on line 3, pos 16", "Error <mismatching types> on line 4, pos 14", "Error <mismatching types> on line 5, pos 13", "Error <mismatching types> on line 8, pos 6", "Error <mismatching types> on line 10, pos 6", "Error <mismatching types> on line 12, pos 6", "Error <mismatching types> on line 14, pos 6", "Error <expected array> on line 16, pos 4", "Error <expected array> on line 17, pos 4", "Error <expected array> on line 18, pos 4", "Error <expected array> on line 19, pos 4" ), "src/test/java/tours/examples/typechecker/invalid/mismatching_type.tours"); } @Test public void testMismatchingTypesArrays() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <mismatching types> on line 3, pos 9", "Error <mismatching types> on line 4, pos 9", "Error <mismatching types> on line 5, pos 9", "Error <mismatching types> on line 7, pos 9", "Error <mismatching types> on line 8, pos 9", "Error <mismatching types> on line 9, pos 9", "Error <mismatching types> on line 11, pos 9", "Error <mismatching types> on line 12, pos 9", "Error <mismatching types> on line 13, pos 9", "Error <mismatching types> on line 15, pos 9", "Error <mismatching types> on line 16, pos 9", "Error <mismatching types> on line 17, pos 9", "Error <mismatching array types> on line 19, pos 20", "Error <mismatching array types> on line 19, pos 20", "Error <mismatching types> on line 19, pos 16", "Error <mismatching array types> on line 20, pos 22", "Error <mismatching array types> on line 20, pos 22", "Error <mismatching types> on line 20, pos 18", "Error <mismatching array types> on line 21, pos 20", "Error <mismatching array types> on line 21, pos 20", "Error <mismatching types> on line 21, pos 16", "Error <mismatching array types> on line 22, pos 19", "Error <mismatching array types> on line 22, pos 19", "Error <mismatching types> on line 22, pos 15", "Error <expected integer> on line 24, pos 6", "Error <expected integer> on line 25, pos 6", "Error <expected integer> on line 26, pos 6", "Error <expected integer> on line 27, pos 6", "Error <expected integer> on line 28, pos 6", "Error <expected integer> on line 29, pos 6", "Error <expected integer> on line 31, pos 30", "Error <expected integer> on line 32, pos 30", "Error <expected integer> on line 33, pos 30" ), "src/test/java/tours/examples/typechecker/invalid/mismatching_type_array.tours"); } @Test public void testMismatchingTypesArrayLength() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <mismatching types> on line 3, pos 15", "Error <mismatching types> on line 6, pos 17", "Error <mismatching types> on line 9, pos 14", "Error <expected array> on line 12, pos 4", "Error <expected array> on line 15, pos 4", "Error <expected array> on line 18, pos 4", "Error <expected array> on line 21, pos 4" ), "src/test/java/tours/examples/typechecker/invalid/mismatching_type_array_length.tours"); } @Test public void testMismatchingTypesArrayReturn() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <mismatching types> on line 22, pos 16", "Error <mismatching types> on line 23, pos 18", "Error <mismatching types> on line 24, pos 16", "Error <mismatching types> on line 25, pos 13" ), "src/test/java/tours/examples/typechecker/invalid/mismatching_type_return_array.tours"); } @Test public void testMismatchingTypesIfElse() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <mismatching types> on line 2, pos 15", "Error <mismatching types> on line 3, pos 17", "Error <mismatching types> on line 4, pos 15", "Error <mismatching types> on line 5, pos 14", "Error <mismatching expression types> on line 7, pos 21", "Error <mismatching expression types> on line 8, pos 23", "Error <mismatching expression types> on line 9, pos 21", "Error <mismatching expression types> on line 10, pos 20" ), "src/test/java/tours/examples/typechecker/invalid/mismatching_type_if_else.tours"); } @Test public void testAlreadyDefinedVariables() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <variable already defined> on line 3, pos 12", "Error <variable already defined> on line 4, pos 14", "Error <variable already defined> on line 7, pos 14", "Error <variable already defined> on line 11, pos 12", "Error <variable already defined> on line 15, pos 12" ), "src/test/java/tours/examples/typechecker/invalid/already_defined_variables.tours"); } @Test public void testAlreadyDefinedFunction() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <function name already defined> on line 4, pos 10", "Error <function name already defined> on line 5, pos 13", "Error <function name already defined> on line 7, pos 13", "Error <function name already defined> on line 8, pos 13" ), "src/test/java/tours/examples/typechecker/invalid/already_defined_function.tours"); } @Test public void testNotDefinedVariables() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <variable not defined> on line 3, pos 6", "Error <variable not defined> on line 5, pos 4", "Error <variable not defined> on line 8, pos 4", "Error <variable not defined> on line 10, pos 6", "Error <variable not defined> on line 13, pos 4", "Error <variable not defined> on line 15, pos 10", "Error <variable not defined> on line 16, pos 10", "Error <variable not defined> on line 20, pos 9", "Error <variable not defined> on line 21, pos 4", "Error <variable not defined> on line 23, pos 9", "Error <variable not defined> on line 24, pos 4", "Error <variable not defined> on line 26, pos 9", "Error <variable not defined> on line 27, pos 4", "Error <variable not defined> on line 29, pos 9", "Error <variable not defined> on line 30, pos 4" ), "src/test/java/tours/examples/typechecker/invalid/not_defined_variables.tours"); } @Test public void testNotDefinedVariablesIf() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <variable not defined> on line 8, pos 10" ), "src/test/java/tours/examples/typechecker/invalid/not_defined_variables_if.tours"); } @Test public void testNotDefinedFunction() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <function not defined> on line 2, pos 4" ), "src/test/java/tours/examples/typechecker/invalid/not_defined_function.tours"); } @Test public void testInvalidBooleanExpressions() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <expected booleans> on line 2, pos 4", "Error <expected booleans> on line 3, pos 4", "Error <expected booleans> on line 4, pos 4", "Error <expected booleans> on line 6, pos 4", "Error <expected booleans> on line 7, pos 4", "Error <expected booleans> on line 8, pos 4", "Error <expected booleans> on line 10, pos 4", "Error <expected booleans> on line 11, pos 4", "Error <expected booleans> on line 12, pos 4", "Error <expected booleans> on line 14, pos 4", "Error <expected booleans> on line 15, pos 4", "Error <expected booleans> on line 16, pos 4" ), "src/test/java/tours/examples/typechecker/invalid/invalid_boolean_expressions.tours"); } @Test public void testInvalidPrefixExpressions() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <expected integer> on line 2, pos 5", "Error <expected integer> on line 3, pos 5", "Error <expected integer> on line 4, pos 5", "Error <expected boolean> on line 6, pos 5", "Error <expected boolean> on line 7, pos 5", "Error <expected boolean> on line 8, pos 5" ), "src/test/java/tours/examples/typechecker/invalid/invalid_prefix_expressions.tours"); } @Test public void testInvalidForStatement() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <expected boolean> on line 6, pos 11", "Error <expected boolean> on line 7, pos 11", "Error <expected boolean> on line 8, pos 11", "Error <mismatching types> on line 9, pos 11", "Error <expected integers> on line 9, pos 11", "Error <expected boolean> on line 10, pos 11", "Error <expected boolean> on line 11, pos 11", "Error <expected boolean> on line 12, pos 11", "Error <expected boolean> on line 13, pos 11", "Error <expected boolean> on line 14, pos 11", "Error <expected boolean> on line 15, pos 11" ), "src/test/java/tours/examples/typechecker/invalid/invalid_statements_for.tours"); } @Test public void testInvalidIfStatement() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <expected boolean> on line 6, pos 7", "Error <expected boolean> on line 7, pos 7", "Error <expected boolean> on line 8, pos 7", "Error <mismatching types> on line 9, pos 8", "Error <expected integers> on line 9, pos 8", "Error <expected boolean> on line 10, pos 7", "Error <expected boolean> on line 11, pos 7", "Error <expected boolean> on line 12, pos 7", "Error <expected boolean> on line 13, pos 7", "Error <expected boolean> on line 14, pos 7", "Error <expected boolean> on line 15, pos 7" ), "src/test/java/tours/examples/typechecker/invalid/invalid_statements_if.tours"); } @Test public void testInvalidWhileStatement() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <expected boolean> on line 6, pos 10", "Error <expected boolean> on line 7, pos 10", "Error <expected boolean> on line 8, pos 10", "Error <mismatching types> on line 9, pos 11", "Error <expected integers> on line 9, pos 11", "Error <expected boolean> on line 10, pos 10", "Error <expected boolean> on line 11, pos 10", "Error <expected boolean> on line 12, pos 10", "Error <expected boolean> on line 13, pos 10", "Error <expected boolean> on line 14, pos 10", "Error <expected boolean> on line 15, pos 10" ), "src/test/java/tours/examples/typechecker/invalid/invalid_statements_while.tours"); } @Test public void testMismatchingFunctionAssignments() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <mismatching types> on line 9, pos 13", "Error <mismatching types> on line 10, pos 14" ), "src/test/java/tours/examples/typechecker/invalid/mismatching_function_assignments.tours"); } @Test public void testMismatchingFunctionReturnType() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <mismatching types> on line 1, pos 27", "Error <mismatching types> on line 5, pos 29", "Error <mismatching types> on line 9, pos 26", "Error <mismatching types> on line 13, pos 25" ), "src/test/java/tours/examples/typechecker/invalid/mismatching_function_return_type.tours"); } @Test public void testMismatchingTypesOnArithmeticExpressions() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <expected integers> on line 2, pos 4", "Error <expected integers> on line 3, pos 4", "Error <expected integers> on line 5, pos 4", "Error <expected integers> on line 6, pos 4", "Error <expected integers> on line 8, pos 4", "Error <expected integers> on line 9, pos 4", "Error <expected integers> on line 11, pos 4", "Error <expected integers> on line 12, pos 4" ), "src/test/java/tours/examples/typechecker/invalid/mismatching_types_arithmetic_expressions.tours"); } @Test public void testMismatchingTypesOnComparisonExpressions() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <mismatching types> on line 2, pos 4", "Error <expected integers> on line 2, pos 4", "Error <mismatching types> on line 3, pos 4", "Error <expected integers> on line 3, pos 4", "Error <mismatching types> on line 4, pos 4", "Error <expected integers> on line 4, pos 4", "Error <mismatching types> on line 5, pos 4", "Error <expected integers> on line 5, pos 4", "Error <mismatching types> on line 7, pos 4", "Error <mismatching types> on line 8, pos 4" ), "src/test/java/tours/examples/typechecker/invalid/mismatching_types_comparison_expressions.tours"); } @Test public void testLengthOnPrimitiveType() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <expected array> on line 3, pos 10", "Error <expected array> on line 6, pos 10", "Error <expected array> on line 9, pos 10", "Error <expected array> on line 12, pos 10" ), "src/test/java/tours/examples/typechecker/invalid/length_on_primitive_type.tours"); } @Test public void testVoidCompoundExpression() { assertEqualTypeCheckErrorList(Arrays.asList( "Error <last type is a void> on line 4, pos 4", "Error <mismatching types> on line 2, pos 14" ), "src/test/java/tours/examples/typechecker/invalid/void_compound_expression.tours"); } private void assertEqualTypeCheckErrorList(List<String> expected, String filename) { try { assertEquals(expected, CompilerTools.typeCheck(filename).getErrors()); } catch (IOException e) { fail(e.getMessage()); } } }
package me.dreamteam.tardis; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Toolkit; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferStrategy; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import org.lwjgl.Sys; import me.dreamteam.tardis.Entity; import me.dreamteam.tardis.ShipEntity; /** Main Class */ public class Game extends Canvas { /** * Begin the game parameters that will allow us to define certain elements. */ private BufferStrategy strategy; // This provides hardware acceleration private boolean isRunning = true; // Is the game running or not? private String gameName = "Codename TARDIS "; private String build = "Alpha "; private String version = "0.1.9"; private Entity ship; private ArrayList entities = new ArrayList(); private double moveSpeed = 250; private boolean leftPressed = false; private boolean rightPressed = false; private boolean spacebarPressed = false; private boolean logicRequiredThisLoop = false; int fps; long lastFPS; // To grab the FPS, for debugging purposes. 60 FPS is the best FPS! public Game() { // create a frame to contain our game JFrame container = new JFrame(gameName + "- " + build + version + " | FPS: " + lastFPS); // get hold the content of the frame and set up the resolution of the game JPanel panel = (JPanel) container.getContentPane(); panel.setPreferredSize(new Dimension(500,650)); panel.setLayout(null); // setup our canvas size and put it into the content of the frame setBounds(0,0,500,650); panel.add(this); // Tell AWT not to bother repainting our canvas since we're // going to do that our self in accelerated mode setIgnoreRepaint(true); //Don't move this variable as it will add extra padding if moved below pack container.setResizable(false); container.pack(); // Make sure the window shows up smack bang in the centre Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); int w = container.getSize().width; int h = container.getSize().height; int x = (dim.width-w)/2; int y = (dim.height-h)/2; container.setLocation(x, y); // Then set the container as visible container.setBackground(Color.black); container.setVisible(true); // add a listener to respond to the user closing the window. If they // do we'd like to exit the game container.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { JOptionPane.showMessageDialog(null, "Closing " + gameName + version); // Debug to ensure that game exits correctly System.exit(0); } }); // Init keys addKeyListener(new KeyInputHandler()); // create the buffering strategy for graphics createBufferStrategy(2); strategy = getBufferStrategy(); requestFocus(); initEntities(); } public void updateLogic() { logicRequiredThisLoop = true; } public void quitGame() { JOptionPane.showMessageDialog(null, "Closing " + gameName + version); // Debug to ensure that game exits correctly System.exit(0); } /** * initialise entities */ private void initEntities() { // create the player ship and place it roughly in the center of the screen ship = new ShipEntity(this,"sprites/ship.png",220,568); entities.add(ship); Entity Enemy = new EnemyEntity(this,"sprites/ship.png",150,50); entities.add(Enemy); } /** * Garbage collection and looping */ private void startGame() { entities.clear(); initEntities(); // reset key presses leftPressed = false; rightPressed = false; spacebarPressed = false; } /** * Calculate the FPS and set it in the title bar */ public void updateFPS() { if (getTime() - lastFPS > 1000) { fps = 0; //reset the FPS counter lastFPS += 1000; //add one second } fps++; } public long getTime() { return (Sys.getTime() * 1000) / Sys.getTimerResolution(); } /** * GAME LOOP and Main below */ public void gameLoop() { long lastLoopTime = System.currentTimeMillis(); while (isRunning) { long delta = System.currentTimeMillis() - lastLoopTime; lastLoopTime = System.currentTimeMillis(); lastFPS = getTime(); // Colour in background Graphics2D g = (Graphics2D) strategy.getDrawGraphics(); g.setColor(Color.black); g.fillRect(0,0,500,650); // Adds the ship into game. for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.move(delta); } if (logicRequiredThisLoop) { for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.doLogic(); } logicRequiredThisLoop = false; } for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.draw(g); } // Clear Graphics g.dispose(); strategy.show(); // Staggers ship movement - cleans up PR ship.setHorizontalMovement(0); // Ship movement if ((leftPressed) && (!rightPressed)) { ship.setHorizontalMovement(-moveSpeed); } else if ((rightPressed) && (!leftPressed)) { ship.setHorizontalMovement(moveSpeed); } try { Thread.sleep(10); } catch (Exception e) {} } } private class KeyInputHandler extends KeyAdapter { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { leftPressed = true; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { rightPressed = true; } if (e.getKeyCode() == KeyEvent.VK_SPACE) { spacebarPressed = true; } if (e.getKeyChar() == 27) { quitGame(); // Quit game using the escape key } } public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { leftPressed = false; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { rightPressed = false; } if (e.getKeyCode() == KeyEvent.VK_SPACE) { spacebarPressed = false; } } } /** * Game Start */ public static void main(String argv[]) { Game g =new Game(); // Start the main game loop g.gameLoop(); } }
package me.dreamteam.tardis; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Toolkit; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferStrategy; import java.net.URL; import java.util.ArrayList; import java.util.Random; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import org.lwjgl.Sys; import me.dreamteam.tardis.Entity; import me.dreamteam.tardis.ShipEntity; import me.dreamteam.tardis.EnemyEntity; import me.dreamteam.tardis.Utils; import me.dreamteam.tardis.UtilsHTML; /** Main Class */ public class Game extends Canvas { private BufferStrategy strategy; // This provides hardware acceleration private boolean isRunning = true; private boolean gameStart = false; private Entity ship; private int shipS = 0; double curY = 0; long lastLoopTime; private ArrayList entities = new ArrayList(); private ArrayList enemies = new ArrayList(); private double moveSpeed = 180; private boolean leftPressed = false; private boolean rightPressed = false; private boolean logicRequiredThisLoop = false; private boolean advanceLevel = false; long lastFrame; long finalTime = 0; private String timeDisplay = ""; private String livesDisplay = ""; int timeMil; public int gameTime = 0; public int gameLives = 3; int SpriteLoc; int SpriteLoc2; int SpriteLoc3; int twait = 0; int CurSprite = 1; ImageIcon blankIcon = new ImageIcon(); Random rSpriteLoc = new Random(); long lastTime; private int level = 1; public Game() { JFrame container = new JFrame(Utils.gameName + "- " + Utils.build + Utils.version); JPanel panel = (JPanel) container.getContentPane(); panel.setPreferredSize(new Dimension(500,650)); panel.setLayout(null); setBounds(0,0,500,650); panel.add(this); setIgnoreRepaint(true); container.setResizable(false); container.pack(); // Window setup Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); int w = container.getSize().width; int h = container.getSize().height; int x = (dim.width-w)/2; int y = (dim.height-h)/2; container.setLocation(x, y); container.setBackground(Color.black); container.setVisible(true); //What to do when user choose to close container.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Utils.quitGame(); } }); ImageIcon icon = new ImageIcon(Utils.iconURL); container.setIconImage(icon.getImage()); // Init keys addKeyListener(new KeyInputHandler()); // create the buffering strategy for graphics createBufferStrategy(2); strategy = getBufferStrategy(); requestFocus(); initEntities(); titleScreen(); } public void updateLogic() { logicRequiredThisLoop = true; } /** * Create our ship */ private void initEntities() { if (shipS == 0) { ship = new ShipEntity(this,"sprites/ship.png",220,568); entities.add(ship); } if (shipS == 1) { ship = new ShipEntity(this,"sprites/ship2.png",220,568); entities.add(ship); } if (shipS == 2) { ship = new ShipEntity(this,"sprites/ship3.png",220,568); entities.add(ship); } } private void updateEnt(){ moveSpeed = 180+(twait*0.7); SpriteLoc = rSpriteLoc.nextInt(200); SpriteLoc2 = 200+rSpriteLoc.nextInt(250); if(SpriteLoc2 < SpriteLoc+56){ if(SpriteLoc2 > SpriteLoc-56){ SpriteLoc2 = SpriteLoc-56; if (SpriteLoc2 > 450) SpriteLoc2 = SpriteLoc-56; } } if(twait != gameTime){ int FinalLoc; if(gameTime >= twait+2 && advanceLevel == false){ twait = gameTime; for(int i = 0; i<2; i++){ if(i==0){ FinalLoc = SpriteLoc; }else{ FinalLoc = SpriteLoc2; } Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50); entities.add(Enemies); CurSprite += 1; if (CurSprite>5) CurSprite=1; } }else if (advanceLevel == true){ if(gameTime>= twait && level ==2){ twait = gameTime; for(int i = 0; i<2; i++){ if(i==0){ FinalLoc = SpriteLoc; }else{ FinalLoc = SpriteLoc2; } Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50, (twait+(100*0.45)-30)); entities.add(Enemies); CurSprite += 1; if (CurSprite>5) CurSprite=1; } }else if(gameTime>= twait && level >2){ twait = gameTime; for(int i = 0; i<2; i++){ if(i==0){ FinalLoc = SpriteLoc; }else{ FinalLoc = SpriteLoc2; } Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50, (twait+(100*0.45)-30)); entities.add(Enemies); CurSprite += 1; if (CurSprite>5) CurSprite=1; } } } } } private void startGame() { entities.clear(); initEntities(); // reset key presses leftPressed = false; rightPressed = false; //reset time timeMil = 0; //reset lives gameLives = 3; level = 1; gameStart = true; twait = 0; gameTime = 0; finalTime = 0; lastLoopTime = System.currentTimeMillis(); } public void characterSelect() { ImageIcon ship1 = new ImageIcon(Utils.ship1URL); ImageIcon ship2 = new ImageIcon(Utils.ship2URL); ImageIcon ship3 = new ImageIcon(Utils.ship3URL); Utils.systemLF(); Object[] coptions = {UtilsHTML.bpcsStart + ship1 + UtilsHTML.bpcsMiddle + Utils.ship1Name + UtilsHTML.bpcsEnd, UtilsHTML.bpcsStart + ship2 + UtilsHTML.bpcsMiddle + Utils.ship2Name + UtilsHTML.bpcsEnd, UtilsHTML.bpcsStart + ship3 + UtilsHTML.bpcsMiddle + Utils.ship3Name + UtilsHTML.bpcsEnd}; int characterS = JOptionPane.showOptionDialog(null, UtilsHTML.csDialog, Utils.csDialogTitle, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, blankIcon, coptions, coptions[0]); if (characterS != 2 && characterS != 1 && characterS != 0) { titleScreen(); } if (characterS == 2) { shipS = 2; startGame(); } if (characterS == 1) { shipS = 1; startGame(); } if (characterS == 0) { shipS = 0; startGame(); } } public void titleScreen() { ImageIcon icon = new ImageIcon(Utils.iconURL); Utils.systemLF(); Object[] options = {Utils.bPlay, Utils.bQuit}; int startG = JOptionPane.showOptionDialog(null, Utils.txtTS, Utils.tsDialogTitle, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, icon, options, options[0]); if (startG != 0 && startG != 1) { Utils.quitGame(); } if (startG == 1) { System.exit(0); } if (startG == 0) { characterSelect(); } } public void pauseGame() { ImageIcon icon = new ImageIcon(Utils.iconURL); Utils.systemLF(); gameStart = false; long LoopTempTime = System.currentTimeMillis(); Object[] options = {Utils.bReturn, Utils.bRestart, Utils.bQuit}; int pauseG = JOptionPane.showOptionDialog(null, Utils.txtPS, Utils.tsDialogTitle, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, icon, options, options[0]); double[] entCurYLoc = new double[entities.size()]; for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entCurYLoc[i] = entity.getVerticalMovement(); entity.setVerticalMovement(0); } if (pauseG != 1 && pauseG != 2) { for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.setVerticalMovement(entCurYLoc[i]); } finalTime = System.currentTimeMillis() - LoopTempTime; gameStart = true; } if (pauseG == 2) { System.exit(0); } if (pauseG == 1) { gameTime = 0; characterSelect(); } } public void gameLoop() { lastLoopTime = System.currentTimeMillis(); while (isRunning) { if(gameStart == true){ long delta = (System.currentTimeMillis()-finalTime) - lastLoopTime; finalTime = 0; lastLoopTime = System.currentTimeMillis(); lastTime = getTime(); updateTime(); // Colour in background Graphics2D g = (Graphics2D) strategy.getDrawGraphics(); g.setColor(Color.black); g.fillRect(0,0,500,650); for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.move(delta); } if (logicRequiredThisLoop) { for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.doLogic(); } logicRequiredThisLoop = false; } for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.draw(g); } if(gameTime >90){ advanceLevel = true; if(gameTime > 200){ level = 3; }else{ level = 2; } } /* * Game Text */ g.setColor(Color.red); g.setFont(new Font("Century Gothic", Font.BOLD, Utils.levelFS)); g.drawString(Utils.txtLevel + level,(500-g.getFontMetrics().stringWidth(Utils.txtLevel + level))/2,18); // Timer g.setColor(Color.white); g.setFont(new Font("Lucida Console", Font.BOLD, Utils.timeFS)); g.drawString(timeDisplay,(70-g.getFontMetrics().stringWidth(timeDisplay))/2,18); g.drawString(Utils.txtTime,(70-g.getFontMetrics().stringWidth(Utils.txtTime))/2,18); if (timeMil > 99){ gameTime = timeMil/100; } String convtime = String.valueOf(gameTime); g.setColor(Color.white); g.setFont(new Font("Lucida Console", Font.ITALIC, Utils.timeIFS)); g.drawString(timeDisplay,(175-g.getFontMetrics().stringWidth(timeDisplay))/2,18); g.drawString(convtime,(175-g.getFontMetrics().stringWidth(convtime))/2,18); //Lives g.setColor(Color.white); g.setFont(new Font("Lucida Console", Font.BOLD, Utils.livesFS)); g.drawString(livesDisplay,(875-g.getFontMetrics().stringWidth(livesDisplay))/2,18); g.drawString(Utils.txtLives,(875-g.getFontMetrics().stringWidth(Utils.txtLives))/2,18); String convlives = String.valueOf(gameLives); g.setColor(Color.white); g.setFont(new Font("Lucida Console", Font.ITALIC, Utils.livesIFS)); g.drawString(timeDisplay,(965-g.getFontMetrics().stringWidth(timeDisplay))/2,18); g.drawString(convlives,(965-g.getFontMetrics().stringWidth(convlives))/2,18); // Clear Graphics g.dispose(); strategy.show(); updateEnt(); ship.setHorizontalMovement(0); // Ship movement if ((leftPressed) && (!rightPressed)) { ship.setHorizontalMovement(-moveSpeed); } else if ((rightPressed) && (!leftPressed)) { ship.setHorizontalMovement(moveSpeed); } //testing for collision of player and enemy for (int p=0;p<entities.size();p++) { for (int s=p+1;s<entities.size();s++) { Entity me = (Entity) entities.get(p); Entity him = (Entity) entities.get(s); if (me.collidesWith(him)) { me.collidedWith(him); him.collidedWith(me); } } } try { Thread.sleep(10); } catch (Exception e) {} }else{ try { Thread.sleep(10); } catch (Exception e) {} } } } /** * Update the game time */ public void updateTime() { if (getTime() - lastTime > 1000) { timeMil = 0; //reset the FPS counter lastTime += 1000; //add one second } timeMil++; } public long getTime() { return (Sys.getTime() * 1000) / Sys.getTimerResolution(); } public int getDelta() { long time = getTime(); int delta = (int) (time - lastFrame); lastFrame = time; return delta; } private class KeyInputHandler extends KeyAdapter { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { leftPressed = true; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { rightPressed = true; } if (e.getKeyChar() == 27) { pauseGame(); } if (e.getKeyCode() == KeyEvent.VK_PAUSE) { pauseGame(); } if (e.getKeyCode() == KeyEvent.VK_P) { pauseGame(); } } public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { leftPressed = false; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { rightPressed = false; } } } public static void main(String argv[]) { Game g =new Game(); // Start the main game loop g.gameLoop(); } }
package me.dreamteam.tardis; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Toolkit; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferStrategy; import java.net.URL; import java.util.ArrayList; import java.util.Random; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import org.lwjgl.Sys; import me.dreamteam.tardis.Entity; import me.dreamteam.tardis.ShipEntity; import me.dreamteam.tardis.EnemyEntity; import me.dreamteam.tardis.Utils; import me.dreamteam.tardis.UtilsHTML; /** Main Class */ public class Game extends Canvas { private BufferStrategy strategy; // This provides hardware acceleration private boolean isRunning = true; private boolean gameStart = false; private Entity ship; private int shipS = 0; private ArrayList entities = new ArrayList(); private ArrayList enemies = new ArrayList(); private double moveSpeed = 180; private boolean leftPressed = false; private boolean rightPressed = false; private boolean logicRequiredThisLoop = false; private boolean advanceLevel = false; long lastFrame; private String timeDisplay = ""; private String livesDisplay = ""; int timeMil; public int gameTime = 0; public int gameLives = 3; int SpriteLoc; int SpriteLoc2; int SpriteLoc3; int twait = 0; int CurSprite = 1; ImageIcon blankIcon = new ImageIcon(); Random rSpriteLoc = new Random(); long lastTime; URL iconURL = getClass().getResource("/sprites/ship.png"); URL ship1URL = getClass().getResource("/sprites/ship.png"); URL ship2URL = getClass().getResource("/sprites/ship2.png"); URL ship3URL = getClass().getResource("/sprites/ship3.png"); private int level = 1; public Game() { JFrame container = new JFrame(Utils.gameName + "- " + Utils.build + Utils.version); JPanel panel = (JPanel) container.getContentPane(); panel.setPreferredSize(new Dimension(500,650)); panel.setLayout(null); setBounds(0,0,500,650); panel.add(this); setIgnoreRepaint(true); container.setResizable(false); container.pack(); // Window setup Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); int w = container.getSize().width; int h = container.getSize().height; int x = (dim.width-w)/2; int y = (dim.height-h)/2; container.setLocation(x, y); container.setBackground(Color.black); container.setVisible(true); //What to do when user choose to close container.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Utils.quitGame(); } }); ImageIcon icon = new ImageIcon(iconURL); container.setIconImage(icon.getImage()); // Init keys addKeyListener(new KeyInputHandler()); // create the buffering strategy for graphics createBufferStrategy(2); strategy = getBufferStrategy(); requestFocus(); initEntities(); titleScreen(); } public void updateLogic() { logicRequiredThisLoop = true; } /** * Create our ship */ private void initEntities() { if (shipS == 0) { ship = new ShipEntity(this,"sprites/ship.png",220,568); entities.add(ship); } if (shipS == 1) { ship = new ShipEntity(this,"sprites/ship2.png",220,568); entities.add(ship); } if (shipS == 2) { ship = new ShipEntity(this,"sprites/ship3.png",220,568); entities.add(ship); } } private void updateEnt(){ moveSpeed = 180+(twait*0.7); SpriteLoc = rSpriteLoc.nextInt(200); SpriteLoc2 = 200+rSpriteLoc.nextInt(250); if(SpriteLoc2 < SpriteLoc+56){ if(SpriteLoc2 > SpriteLoc-56){ SpriteLoc2 = SpriteLoc-56; if (SpriteLoc2 > 450) SpriteLoc2 = SpriteLoc-56; } } if(twait != gameTime){ int FinalLoc; if(gameTime >= twait+2 && advanceLevel == false){ twait = gameTime; for(int i = 0; i<2; i++){ if(i==0){ FinalLoc = SpriteLoc; }else{ FinalLoc = SpriteLoc2; } Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50); entities.add(Enemies); CurSprite += 1; if (CurSprite>5) CurSprite=1; } }else if (advanceLevel == true){ if(gameTime>= twait && level ==2){ twait = gameTime; for(int i = 0; i<2; i++){ if(i==0){ FinalLoc = SpriteLoc; }else{ FinalLoc = SpriteLoc2; } Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50, (twait+(100*0.45)-30)); entities.add(Enemies); CurSprite += 1; if (CurSprite>5) CurSprite=1; } }else if(gameTime>= twait && level >2){ twait = gameTime; for(int i = 0; i<2; i++){ if(i==0){ FinalLoc = SpriteLoc; }else{ FinalLoc = SpriteLoc2; } Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50, (twait+(100*0.45)-30)); entities.add(Enemies); CurSprite += 1; if (CurSprite>5) CurSprite=1; } } } } } private void startGame() { entities.clear(); initEntities(); // reset key presses leftPressed = false; rightPressed = false; //reset time timeMil = 0; //reset lives gameLives = 3; level = 1; gameStart = true; } public void characterSelect() { ImageIcon ship1 = new ImageIcon(ship1URL); ImageIcon ship2 = new ImageIcon(ship2URL); ImageIcon ship3 = new ImageIcon(ship3URL); Utils.systemLF(); Object[] coptions = {UtilsHTML.bpcsStart + ship1 + UtilsHTML.bpcsMiddle + Utils.ship1Name + UtilsHTML.bpcsEnd, UtilsHTML.bpcsStart + ship2 + UtilsHTML.bpcsMiddle + Utils.ship2Name + UtilsHTML.bpcsEnd, UtilsHTML.bpcsStart + ship3 + UtilsHTML.bpcsMiddle + Utils.ship3Name + UtilsHTML.bpcsEnd}; int characterS = JOptionPane.showOptionDialog(null, UtilsHTML.csDialog, Utils.csDialogTitle, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, blankIcon, coptions, coptions[0]); if (characterS != 2 && characterS != 1 && characterS != 0) { titleScreen(); } if (characterS == 2) { shipS = 2; startGame(); } if (characterS == 1) { shipS = 1; startGame(); } if (characterS == 0) { shipS = 0; startGame(); } } public void titleScreen() { ImageIcon icon = new ImageIcon(iconURL); Utils.systemLF(); Object[] options = {Utils.bPlay, Utils.bQuit}; int startG = JOptionPane.showOptionDialog(null, Utils.txtTS, Utils.tsDialogTitle, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, icon, options, options[0]); if (startG != 0 && startG != 1) { Utils.quitGame(); } if (startG == 1) { System.exit(0); } if (startG == 0) { characterSelect(); } } public void restartGame() { ImageIcon icon = new ImageIcon(iconURL); Utils.systemLF(); gameStart = false; Object[] options = {Utils.bRestart, Utils.bQuit}; int startG = JOptionPane.showOptionDialog(null, Utils.rtxtCS, Utils.tsDialogTitle, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, icon, options, options[0]); if (startG != 0 && startG != 1) { gameStart = true; } if (startG == 1) { System.exit(0); } if (startG == 0) { characterSelect(); } } public void gameLoop() { long lastLoopTime = System.currentTimeMillis(); while (isRunning) { if(gameStart == true){ long delta = System.currentTimeMillis() - lastLoopTime; lastLoopTime = System.currentTimeMillis(); lastTime = getTime(); updateTime(); // Colour in background Graphics2D g = (Graphics2D) strategy.getDrawGraphics(); g.setColor(Color.black); g.fillRect(0,0,500,650); for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.move(delta); } if (logicRequiredThisLoop) { for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.doLogic(); } logicRequiredThisLoop = false; } for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.draw(g); } if(gameTime >90){ advanceLevel = true; if(gameTime > 200){ level = 3; }else{ level = 2; } } /* * Game Text */ g.setColor(Color.red); g.setFont(new Font("Century Gothic", Font.BOLD, Utils.levelFS)); g.drawString(Utils.txtLevel + level,(500-g.getFontMetrics().stringWidth(Utils.txtLevel + level))/2,18); // Timer g.setColor(Color.white); g.setFont(new Font("Lucida Console", Font.BOLD, Utils.timeFS)); g.drawString(timeDisplay,(70-g.getFontMetrics().stringWidth(timeDisplay))/2,18); g.drawString(Utils.txtTime,(70-g.getFontMetrics().stringWidth(Utils.txtTime))/2,18); if (timeMil > 99){ gameTime = timeMil/100; } String convtime = String.valueOf(gameTime); g.setColor(Color.white); g.setFont(new Font("Lucida Console", Font.ITALIC, Utils.timeIFS)); g.drawString(timeDisplay,(175-g.getFontMetrics().stringWidth(timeDisplay))/2,18); g.drawString(convtime,(175-g.getFontMetrics().stringWidth(convtime))/2,18); //Lives g.setColor(Color.white); g.setFont(new Font("Lucida Console", Font.BOLD, Utils.livesFS)); g.drawString(livesDisplay,(875-g.getFontMetrics().stringWidth(livesDisplay))/2,18); g.drawString(Utils.txtLives,(875-g.getFontMetrics().stringWidth(Utils.txtLives))/2,18); String convlives = String.valueOf(gameLives); g.setColor(Color.white); g.setFont(new Font("Lucida Console", Font.ITALIC, Utils.livesIFS)); g.drawString(timeDisplay,(965-g.getFontMetrics().stringWidth(timeDisplay))/2,18); g.drawString(convlives,(965-g.getFontMetrics().stringWidth(convlives))/2,18); // Clear Graphics g.dispose(); strategy.show(); updateEnt(); ship.setHorizontalMovement(0); // Ship movement if ((leftPressed) && (!rightPressed)) { ship.setHorizontalMovement(-moveSpeed); } else if ((rightPressed) && (!leftPressed)) { ship.setHorizontalMovement(moveSpeed); } //testing for collision of player and enemy for (int p=0;p<entities.size();p++) { for (int s=p+1;s<entities.size();s++) { Entity me = (Entity) entities.get(p); Entity him = (Entity) entities.get(s); if (me.collidesWith(him)) { me.collidedWith(him); him.collidedWith(me); } } } try { Thread.sleep(10); } catch (Exception e) {} }else{ try { Thread.sleep(10); } catch (Exception e) {} } } } /** * Update the game time */ public void updateTime() { if (getTime() - lastTime > 1000) { timeMil = 0; //reset the FPS counter lastTime += 1000; //add one second } timeMil++; } public long getTime() { return (Sys.getTime() * 1000) / Sys.getTimerResolution(); } public int getDelta() { long time = getTime(); int delta = (int) (time - lastFrame); lastFrame = time; return delta; } private class KeyInputHandler extends KeyAdapter { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { leftPressed = true; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { rightPressed = true; } if (e.getKeyChar() == 27) { restartGame(); } } public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { leftPressed = false; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { rightPressed = false; } } } public static void main(String argv[]) { Game g =new Game(); // Start the main game loop g.gameLoop(); } }
package storage; public class Highscores { // ATTRIBUTES private int id; private String name; private String tokenFigure; private int amount; private String date; // CONSTRUCTOR public Highscores(int id, String name, String tokenFigure, int amount, String date){ this.id = id; this.name = name; this.tokenFigure = tokenFigure; this.amount = amount; this.date = date; } // METHODS public int getID(){ return id; } public String getName(){ return name; } public String getTokenFigure(){ return tokenFigure; } public int getAmount(){ return amount; } public String getDate(){ return date; } }
package hudson.util; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.ListIterator; import java.util.AbstractList; import java.util.Arrays; /** * Varios {@link Iterator} implementations. * * @author Kohsuke Kawaguchi * @see AdaptedIterator */ public class Iterators { /** * Returns the empty iterator. */ public static <T> Iterator<T> empty() { return Collections.<T>emptyList().iterator(); } /** * Produces {A,B,C,D,E,F} from {{A,B},{C},{},{D,E,F}}. */ public static abstract class FlattenIterator<U,T> implements Iterator<U> { private final Iterator<? extends T> core; private Iterator<U> cur; protected FlattenIterator(Iterator<? extends T> core) { this.core = core; cur = Collections.<U>emptyList().iterator(); } protected FlattenIterator(Iterable<? extends T> core) { this(core.iterator()); } protected abstract Iterator<U> expand(T t); public boolean hasNext() { while(!cur.hasNext()) { if(!core.hasNext()) return false; cur = expand(core.next()); } return true; } public U next() { if(!hasNext()) throw new NoSuchElementException(); return cur.next(); } public void remove() { throw new UnsupportedOperationException(); } } /** * Creates a filtered view of another iterator. * * @since 1.150 */ public static abstract class FilterIterator<T> implements Iterator<T> { private final Iterator<? extends T> core; private T next; private boolean fetched; protected FilterIterator(Iterator<? extends T> core) { this.core = core; } protected FilterIterator(Iterable<? extends T> core) { this(core.iterator()); } private void fetch() { while(!fetched && core.hasNext()) { T n = core.next(); if(filter(n)) { next = n; fetched = true; } } } /** * Filter out items in the original collection. * * @return * true to leave this item and return this item from this iterator. * false to hide this item. */ protected abstract boolean filter(T t); public boolean hasNext() { fetch(); return fetched; } public T next() { fetch(); if(!fetched) throw new NoSuchElementException(); fetched = false; return next; } public void remove() { core.remove(); } } /** * Returns the {@link Iterable} that lists items in the reverse order. * * @since 1.150 */ public static <T> Iterable<T> reverse(final List<T> lst) { return new Iterable<T>() { public Iterator<T> iterator() { final ListIterator<T> itr = lst.listIterator(lst.size()); return new Iterator<T>() { public boolean hasNext() { return itr.hasPrevious(); } public T next() { return itr.previous(); } public void remove() { itr.remove(); } }; } }; } /** * Returns a list that represents [start,end). * * For example sequence(1,5,1)={1,2,3,4}, and sequence(7,1,-2)={7.5,3} * * @since 1.150 */ public static List<Integer> sequence(final int start, int end, final int step) { final int size = (end-start)/step; if(size<0) throw new IllegalArgumentException("List size is negative"); return new AbstractList<Integer>() { public Integer get(int index) { if(index<0 || index>=size) throw new IndexOutOfBoundsException(); return start+index*step; } public int size() { return size; } }; } public static List<Integer> sequence(int start, int end) { return sequence(start,end,1); } /** * The short cut for {@code reverse(sequence(start,end,step))}. * * @since 1.150 */ public static List<Integer> reverseSequence(int start, int end, int step) { return sequence(end-1,start-1,-step); } public static List<Integer> reverseSequence(int start, int end) { return reverseSequence(start,end,1); } /** * Casts {@link Iterator} by taking advantage of its covariant-ness. */ @SuppressWarnings({"unchecked"}) public static <T> Iterator<T> cast(Iterator<? extends T> itr) { return (Iterator)itr; } /** * Casts {@link Iterable} by taking advantage of its covariant-ness. */ @SuppressWarnings({"unchecked"}) public static <T> Iterable<T> cast(Iterable<? extends T> itr) { return (Iterable)itr; } /** * Creates a read-only mutator that disallows {@link Iterator#remove()}. */ public static <T> Iterator<T> readOnly(final Iterator<T> itr) { return new Iterator<T>() { public boolean hasNext() { return itr.hasNext(); } public T next() { return itr.next(); } public void remove() { throw new UnsupportedOperationException(); } }; } /** * Returns an {@link Iterable} that iterates over all the given {@link Iterable}s. * * <p> * That is, this creates {A,B,C,D} from {A,B},{C,D}. */ public static <T> Iterable<T> sequence( final Iterable<? extends T>... iterables ) { return new Iterable<T>() { public Iterator<T> iterator() { return new FlattenIterator<T,Iterable<? extends T>>(Arrays.asList(iterables)) { protected Iterator<T> expand(Iterable<? extends T> iterable) { return cast(iterable).iterator(); } }; } }; } }
package utilities; import play.i18n.Messages; import models.Cabin; import models.LargeCabin; import models.SmallCabin; import flexjson.JSONDeserializer; /** * Subclass of AbstractForm. Binds and validate json data used to create * a Cabin in the booking system. * @author Olav * */ public class CabinForm extends AbstractForm<Cabin>{ public String type; public String name; public int beds; public int id; /** * FlexJson needs an constructor even if its empty */ public CabinForm() { } /** * CreateModel creates an Cabin and saves it to the database. * If the form is not valid, it returns null. */ @Override public boolean validate() { if(type == null) { this.addError(Messages.get("cabin.missingType")); return false; } if(!(type.equals("LargeCabin") || type.equals("SmallCabin"))) { this.addError(Messages.get("cabin.invalidType")); return false; } if(name == null) { this.addError(Messages.get("cabin.missingName")); return false; } return true; } /** * Validate is responsible for checking that no data is missing from the json request, * and that data is correctly inputed. If there is any missing or wrong * parameters, then the form is deemed invalid. */ @Override public Cabin createModel() { if(isValid()) { if(this.type.equals("SmallCabin")) { SmallCabin cabin = new SmallCabin(this.name); return cabin; } else if(this.type.equals("LargeCabin")) { LargeCabin cabin = new LargeCabin(this.name, this.beds); return cabin; } } return null; } public String toString() { return "type: " +type + " ,name: " +name +" ,beds: " + beds + " ,id: " +id; } /** * jsonFlex is used to deserialize/unmarshall json String into a form containing * java classes like String, int, List<T>. If the deserializer cant complete, * it is counted as an error. * * @param jsonBooking * @return CabinForm used to validate and bind the data. */ public static CabinForm deserializeJson(String jsonCabin) { CabinForm cabinData = null; try { JSONDeserializer<CabinForm> deserializer = new JSONDeserializer<CabinForm>(); cabinData = deserializer.deserialize(jsonCabin , CabinForm.class); } catch (Exception e) { //add more detailed data. Possibly what variable it cant find. cabinData = new CabinForm(); cabinData.addError(Messages.get("json.couldNotParseData")); } return cabinData; } }
package jlibs.core.lang; import java.util.Arrays; /** * Class used to count by units * * @author Santhosh Kumar T */ public class Count<T extends Count.Unit> implements Comparable<Count<T>>{ private long amounts[]; private T units[]; private Count(T units[]){ this.units = units; amounts = new long[units.length]; } static interface Unit{ public int ordinal(); public int count(); public String toString(); } public static <T extends Unit> Count<T> newInstance(Class<T> unitClass){ if(!unitClass.isEnum()) throw new IllegalArgumentException(unitClass+" should be enum"); return new Count<T>(unitClass.getEnumConstants()); } public Count<T> add(long amount, T unit){ if(amount<0) throw new IllegalArgumentException("amount '"+amount+"' should be >=0"); if(amount>0){ amounts[unit.ordinal()] += amount; for(int i=unit.ordinal(); i<units.length-1; i++){ if(amounts[i]>=units[i].count()){ amounts[i+1] += amounts[i] / units[i].count(); amounts[i] %= units[i].count(); }else break; } } return this; } public Count<T> add(Count<T> other){ for(T unit: units) add(other.amounts[unit.ordinal()], unit); return this; } public long get(T unit){ return amounts[unit.ordinal()]; } public strictfp double to(T unit){ long value = amounts[units.length-1]; for(int i=units.length-2; i>=unit.ordinal(); i value = amounts[i]+ units[i].count()*value; if(unit.ordinal()>0){ double before = amounts[0]; for(int i=1; i<unit.ordinal(); i++) before = before/units[i-1].count() + amounts[i]; return value + before/units[unit.ordinal()-1].count(); } return value; } @Override public int hashCode(){ long hash = 0; for(long amount: amounts) hash =31*hash + amount; return (int)(hash ^ hash>>>32); } @Override public boolean equals(Object obj){ if(obj instanceof Count){ Count<?> that = (Count<?>)obj; return Arrays.equals(this.units, that.units) && Arrays.equals(this.amounts, that.amounts); } return false; } public String toString(){ StringBuilder buff = new StringBuilder(); for(int i=units.length-1; i>=0; i if(amounts[i]>0){ if(buff.length()>0) buff.append(' '); buff.append(amounts[i]); buff.append(' '); buff.append(units[i]); } } return buff.length()==0 ? "0 "+units[0].ordinal() : buff.toString(); } @Override public int compareTo(Count<T> that){ for(int i=units.length-1; i>=0; i if(this.amounts[i]!=that.amounts[i]) return this.amounts[i]<that.amounts[i] ? -1 : +1; } return 0; } }
package com.battlelancer.seriesguide.util; import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.api.client.json.jackson.JacksonFactory; import com.battlelancer.seriesguide.backend.CloudEndpointUtils; import com.battlelancer.seriesguide.backend.settings.HexagonSettings; import com.battlelancer.seriesguide.items.SearchResult; import com.battlelancer.seriesguide.provider.SeriesContract; import com.uwetrottmann.seriesguide.shows.Shows; import com.uwetrottmann.seriesguide.shows.model.CollectionResponseShow; import com.uwetrottmann.seriesguide.shows.model.Show; import com.uwetrottmann.seriesguide.shows.model.ShowList; import android.content.ContentProviderOperation; import android.content.ContentValues; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import static com.battlelancer.seriesguide.sync.SgSyncAdapter.UpdateResult; /** * Common activities and tools useful when interacting with shows. */ public class ShowTools { private static ShowTools _instance; private final Context mContext; private final GoogleAccountCredential mCredential; private final Shows mShowsService; public static synchronized ShowTools get(Context context) { if (_instance == null) { _instance = new ShowTools(context); } return _instance; } private ShowTools(Context context) { mContext = context; // get registered Google account mCredential = GoogleAccountCredential.usingAudience(context, HexagonSettings.AUDIENCE); setShowsServiceAccountName(HexagonSettings.getAccountName(context)); // build show service endpoint Shows.Builder builder = new Shows.Builder( AndroidHttp.newCompatibleTransport(), new JacksonFactory(), mCredential ); mShowsService = CloudEndpointUtils.updateBuilder(builder).build(); } public void setShowsServiceAccountName(String accountName) { mCredential.setSelectedAccountName(accountName); } /** * Sends new removed flag, if signed in, up into the cloud. */ public void sendIsRemoved(int showTvdbId, boolean isRemoved) { if (isSignedIn()) { // send to cloud Show show = new Show(); show.setTvdbId(showTvdbId); show.setIsRemoved(isRemoved); uploadShow(show); } } /** * Saves new favorite flag to the local database and, if signed in, up into the cloud as well. */ public void storeIsFavorite(int showTvdbId, boolean isFavorite) { // save to local database ContentValues values = new ContentValues(); values.put(SeriesContract.Shows.FAVORITE, isFavorite); mContext.getContentResolver().update( SeriesContract.Shows.buildShowUri(showTvdbId), values, null, null); if (isSignedIn()) { // send to cloud Show show = new Show(); show.setTvdbId(showTvdbId); show.setIsFavorite(isFavorite); uploadShow(show); } } /** * Saves new hidden flag to the local database and, if signed in, up into the cloud as well. */ public void storeIsHidden(int showTvdbId, boolean isHidden) { // save to local database ContentValues values = new ContentValues(); values.put(SeriesContract.Shows.HIDDEN, isHidden); mContext.getContentResolver().update( SeriesContract.Shows.buildShowUri(showTvdbId), values, null, null); if (isSignedIn()) { // send to cloud Show show = new Show(); show.setTvdbId(showTvdbId); show.setIsHidden(isHidden); uploadShow(show); } } /** * Saves new GetGlue id to the local database and, if signed in, up into the cloud as well. */ public void storeGetGlueId(int showTvdbId, String getglueId) { // save to local database ContentValues values = new ContentValues(); values.put(SeriesContract.Shows.GETGLUEID, getglueId); mContext.getContentResolver() .update(SeriesContract.Shows.buildShowUri(showTvdbId), values, null, null); if (isSignedIn()) { // send to cloud Show show = new Show(); show.setTvdbId(showTvdbId); show.setGetGlueId(getglueId); uploadShow(show); } } public boolean isSignedIn() { return mCredential.getSelectedAccountName() != null; } private void uploadShow(Show show) { List<Show> shows = new LinkedList<>(); shows.add(show); new ShowsUploadTask(mShowsService, shows).execute(); } private static class ShowsUploadTask extends AsyncTask<Void, Void, Void> { private static final String TAG = "ShowTools.Upload"; private final Shows mShowsService; private final List<Show> mShows; public ShowsUploadTask(Shows showsService, List<Show> shows) { mShowsService = showsService; mShows = shows; } @Override protected Void doInBackground(Void... params) { ShowList showList = new ShowList(); showList.setShows(mShows); Log.d(TAG, "Uploading show(s)..."); // upload shows try { mShowsService.save(showList).execute(); } catch (IOException e) { Log.w(TAG, e.getMessage(), e); } Log.d(TAG, "Uploading show(s)...DONE"); return null; } } public static class Download { private static final String TAG = "ShowTools.Download"; public static UpdateResult getAllRemoteShows(Context context, HashSet<Integer> showsExisting, HashMap<Integer, SearchResult> showsNew) { // download shows CollectionResponseShow remoteShows = null; try { remoteShows = ShowTools.get(context).mShowsService.list().execute(); } catch (IOException e) { Log.w(TAG, e.getMessage(), e); } // abort if no response if (remoteShows == null) { return UpdateResult.INCOMPLETE; } // extract list of remote shows List<Show> shows = remoteShows.getItems(); if (shows == null || shows.size() == 0) { return UpdateResult.SUCCESS; } // update all received shows, ContentProvider will ignore those not added locally ArrayList<ContentProviderOperation> batch = buildShowUpdateOps(shows, showsExisting, showsNew); DBUtils.applyInSmallBatches(context, batch); return UpdateResult.SUCCESS; } private static ArrayList<ContentProviderOperation> buildShowUpdateOps(List<Show> shows, HashSet<Integer> showsExisting, HashMap<Integer, SearchResult> showsNew) { ArrayList<ContentProviderOperation> batch = new ArrayList<>(); ContentValues values = new ContentValues(); for (Show show : shows) { // skip shows not in local database if (!showsExisting.contains(show.getTvdbId())) { // skip shows flagged as removed if (show.getIsRemoved() != null && show.getIsRemoved()) { continue; } if (!showsNew.containsKey(show.getTvdbId())) { // add show later SearchResult item = new SearchResult(); item.tvdbid = show.getTvdbId(); item.title = ""; showsNew.put(show.getTvdbId(), item); } // do not create an update op for show continue; } putSyncedShowPropertyValues(show, values); // build update op ContentProviderOperation op = ContentProviderOperation .newUpdate(SeriesContract.Shows.buildShowUri(show.getTvdbId())) .withValues(values).build(); batch.add(op); // clean up for re-use values.clear(); } return batch; } private static void putSyncedShowPropertyValues(Show show, ContentValues values) { putPropertyValueIfNotNull(values, SeriesContract.Shows.FAVORITE, show.getIsFavorite()); putPropertyValueIfNotNull(values, SeriesContract.Shows.HIDDEN, show.getIsHidden()); putPropertyValueIfNotNull(values, SeriesContract.Shows.SYNCENABLED, show.getIsSyncEnabled()); putPropertyValueIfNotNull(values, SeriesContract.Shows.GETGLUEID, show.getGetGlueId()); } private static void putPropertyValueIfNotNull(ContentValues values, String key, Boolean value) { if (value != null) { values.put(key, value.booleanValue()); } } private static void putPropertyValueIfNotNull(ContentValues values, String key, String value) { if (value != null) { values.put(key, value); } } } }
package test.main; import edu.wpi.first.wpilibj.Talon; /** * The RobotMap is a mapping from the ports sensors and actuators are wired into * to a variable name. This provides flexibility changing wiring, makes checking * the wiring easier and significantly reduces the number of magic numbers * floating around. */ public class RobotMap { public static Talon leftCatapult; public static Talon rightCatapult; public static void init(){ leftCatapult = new Talon(2); rightCatapult = new Talon(6); } // For example to map the left and right motors, you could define the // following variables to use with your drivetrain subsystem. // public static final int leftMotor = 1; // public static final int rightMotor = 2; // If you are using multiple modules, make sure to define both the port // number and the module. For example you with a rangefinder: // public static final int rangefinderPort = 1; // public static final int rangefinderModule = 1; }
package userprofile.controller; import foodmood.ExternalDataCntl; import foodmood.controller.NavigationCntl; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import userprofile.model.User; import userprofile.model.UserList; import userprofile.view.UserProfileUI; /** * * @author Michael Kramer */ public class UserCntl { private UserList theUserList; private UserProfileUI userProfileUI; private NavigationCntl navigationCntl; private ExternalDataCntl externalDataCntl; private User user; public UserCntl (UserList theUserList, NavigationCntl navigationCntl) { externalDataCntl = new ExternalDataCntl(); this.theUserList = theUserList; this.navigationCntl = navigationCntl; this.user = navigationCntl.getActiveUser(); System.out.println("Created a UserController."); } public UserCntl (NavigationCntl navigationCntl) { externalDataCntl = new ExternalDataCntl(); this.theUserList = externalDataCntl.readLogins(); this.navigationCntl = navigationCntl; this.user = navigationCntl.getActiveUser(); System.out.println("Created a UserController."); } public void goHome(){ navigationCntl.goHomeScreen(); } public void goUserProfile(){ UserProfileUI userProfileUI = new UserProfileUI(this, user); userProfileUI.setVisible(true); } public boolean submitUser() { System.out.println("UserCntl.submitUser()"); boolean[] testResults = validateNewUserInput(); boolean failedATest = false; for(int i = 0; i < testResults.length; i++) { //If it has not already failed a test and did not pass the test if(!failedATest && !testResults[i]) { failedATest = true; } switch (i) { case 0: // The Username is already Taken userProfileUI.displayUsernameTakenError(testResults[0]); break; case 1: //The Password does not meet the requirements userProfileUI. displayPasswordRequirementsError(testResults[1]); break; case 2: //The entered Passwords do not match userProfileUI.displayPasswordMatchError(testResults[2]); break; default: /* Some error was detected this shouldn't happen unless the number of test is expaned without expanding this switch */ break; } } userProfileUI.pack(); //If it passed all the tests if(!failedATest) { theUserList.addUser(userProfileUI.getUsername(), userProfileUI.getPassword()); System.out.println("The user was added to the userlist."); addUserToDB(userProfileUI.getUsername(), userProfileUI.getPassword()); return true; } else { System.out.println("There were errors with the information entered" + " the user was not added to the userList."); } return false; } /** * This method goes to the UserProfileUI and validates User input. * * @return returns a boolean[] of test results */ public boolean[] validateNewUserInput() { //This method fetches the differe System.out.println("validateNewUserInput()"); boolean[] testResults = new boolean[3]; System.out.println("Checking Username"); /* Checking username is simply verifying that there is not a user, in theUserList, with that username already. */ String username = userProfileUI.getUsername(); System.out.println("Detected Username as: " + username); //If it does not have user name it passes testResults[0] = !theUserList.hasUser(username); if(theUserList.hasUser(username)) { System.out.println("There is already a user with that username."); } else { System.out.println("That username is free."); } System.out.println("Checking Password"); /* Checking the passwor is a two parter, first checking that the two passwords that are entered match, and then validating that the entered password meet the password requirements. */ char[] password = this.userProfileUI.getPassword(); char[] confirmPassword = this.userProfileUI.getConfirmPassword(); //if it is valid password it passes if(User.isValidPassword(password)) { System.out.println("The password entered is a valid password."); testResults[1] = true; } else { System.out.println("The password entered is not a valid password."); testResults[1] = false; } //if the password match it passes if(Arrays.equals(password, confirmPassword)) { System.out.println("The two entered passwords match"); testResults[2] = true; } else { System.out.println("The two entered passwords do not match"); testResults[2] = false; } return testResults; } public void deleteUser(String username, char[] password) { theUserList.deleteUser(username, password); externalDataCntl.deleteUser(username); } public void registerNewUser() { userProfileUI = new UserProfileUI(this); userProfileUI.setVisible(true); userProfileUI.pack(); } public void addUserToDB(String username, char[] password){ theUserList.addUser(username, password); externalDataCntl.addUser(username, password); } public void updateUser(String oldUsername, User newUser){ for (int i = 0; i < theUserList.size(); i++) { if(theUserList.get(i).getUsername().equals(oldUsername)){ theUserList.set(i, newUser); } } externalDataCntl.updateUser(oldUsername, newUser); } }
package torrent.download.tracker; import java.io.IOException; import java.util.LinkedList; import org.johnnei.utils.ThreadUtils; import torrent.download.Torrent; import torrent.download.peer.Peer; import torrent.download.peer.PeerConnectInfo; import torrent.encoding.SHA1; import torrent.network.BitTorrentSocket; import torrent.protocol.BitTorrentHandshake; import torrent.protocol.BitTorrentUtil; import torrent.util.StringUtil; public class PeerConnector implements Runnable { private final Object LOCK_PEER_LIST = new Object(); /** * The object on which the thread will start sleeping once it is out of work */ public final Object PEER_JOB_NOTIFY = new Object(); /** * List of peer that are currently being connected */ private LinkedList<PeerConnectInfo> peers; private TrackerManager manager; private final int maxPeers; public PeerConnector(TrackerManager manager, int maxConnecting) { this.manager = manager; this.maxPeers = maxConnecting; peers = new LinkedList<>(); } /** * Adds a pending connection peer to the connection cycle * * @param peerInfo The peer to connect */ public void addPeer(PeerConnectInfo peerInfo) { if (peers.size() >= maxPeers) { throw new IllegalStateException(String.format("Connector is full")); } synchronized (LOCK_PEER_LIST) { peers.add(peerInfo); } } public void run() { while (true) { if (peers.isEmpty()) { ThreadUtils.wait(PEER_JOB_NOTIFY); } PeerConnectInfo peerInfo = null; BitTorrentSocket peerSocket = null; synchronized (LOCK_PEER_LIST) { peerInfo = peers.remove(); } if (peerInfo == null) { continue; } try { peerSocket = new BitTorrentSocket(); peerSocket.connect(peerInfo.getAddress()); peerSocket.sendHandshake(manager.getPeerId(), peerInfo.getTorrent().getHashArray()); long timeWaited = 0; while (!peerSocket.canReadMessage() && timeWaited < 10_000) { final int INTERVAL = 100; ThreadUtils.sleep(INTERVAL); timeWaited += INTERVAL; } if (!peerSocket.canReadMessage()) { throw new IOException("Handshake timeout"); } BitTorrentHandshake handshake = checkHandshake(peerSocket, peerInfo.getTorrent().getHashArray()); Peer peer = new Peer(peerSocket, peerInfo.getTorrent()); peer.getExtensions().register(handshake.getPeerExtensionBytes()); BitTorrentUtil.onPostHandshake(peer); } catch (IOException e) { System.err.println(String.format("[PeerConnector] Failed to connect peer: %s", e.getMessage())); if (peerSocket != null) { peerSocket.close(); } } } } private BitTorrentHandshake checkHandshake(BitTorrentSocket peerSocket, byte[] torrentHash) throws IOException { BitTorrentHandshake handshake = peerSocket.readHandshake(); if (!SHA1.match(torrentHash, handshake.getTorrentHash())) { throw new IOException(String.format("Peer does not download the same torrent (Expected: %s, Got: %s)", StringUtil.byteArrayToString(torrentHash), StringUtil.byteArrayToString(handshake.getTorrentHash()))); } return handshake; } public int getFreeCapacity() { return maxPeers - peers.size(); } public int getConnectingCount() { return peers.size(); } public int getMaxCapacity() { return maxPeers; } public int getConnectingCountFor(Torrent torrent) { LinkedList<PeerConnectInfo> peerList = null; synchronized (LOCK_PEER_LIST) { peerList = new LinkedList<>(peers); } return (int) peerList.stream(). filter(p -> p.getTorrent().equals(torrent)). count(); } }
package waffle.jetty; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.jasper.servlet.JspServlet; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.webapp.WebAppContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A simple embedded server that lets us run directly within Eclipse. */ public class StartEmbeddedJetty { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(StartEmbeddedJetty.class); /** * Main method. * * @param args * input arguments to main. * @throws Exception * Exception thrown. */ public static void main(final String[] args) throws Exception { final String path = "../waffle-demo/waffle-filter"; final File dir = new File(path); if (!dir.exists()) { throw new FileNotFoundException("Can not find webapp: " + dir.getAbsolutePath()); } final Server server = new Server(8080); final WebAppContext context = new WebAppContext(); context.setServer(server); context.setContextPath("/"); context.setWar(path); // Try adding JSP final ServletHolder jsp = context.addServlet(JspServlet.class, "*.jsp"); jsp.setInitParameter("classpath", context.getClassPath()); server.setHandler(context); try { StartEmbeddedJetty.LOGGER.info(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP"); server.start(); if (System.in.read() == -1) { StartEmbeddedJetty.LOGGER.error("End of Stream reached"); return; } StartEmbeddedJetty.LOGGER.info(">>> STOPPING EMBEDDED JETTY SERVER"); server.stop(); server.join(); } catch (final IOException e) { StartEmbeddedJetty.LOGGER.error("{}", e); System.exit(100); } catch (final Exception e) { StartEmbeddedJetty.LOGGER.error("{}", e); System.exit(100); } } }
package com.btran.bu.sudokusolver; import android.app.AlertDialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.GridLayout; import com.btran.bu.sudokusolver.fragment.SettingsDialogFragment; import com.btran.bu.sudokusolver.promotionAlarm.AlarmService; import com.btran.bu.sudokusolver.util.SudokuUtil; import com.btran.bu.sudokusolver.widget.Cell; public class MainActivity extends ActionBarActivity { public final static String EXTRA_CELLS = "com.btran.bu.sudokusolver.CELLS"; public final static String EXTRA_EMPTY_CHECK = "com.btran.bu.sudokusolver.EMPTY_CHECK"; private final static int NOTIFICATION_DELAY = 1000; private Cell[] _cells; /** * Override onCreate and initialize the Sudoku app. * * @param savedInstanceState */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { // initialize the board initialize(); } else { Log.i("Saved Instance", "Reset board"); if (_cells != null) { resetSudokuBoard(); } } } @Override protected void onStop() { super.onStop(); new AlarmService(this).startAlarm(NOTIFICATION_DELAY); } @Override public void onBackPressed() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder .setTitle("Exit Sudoku Solver?") .setMessage("Are you sure you want to exit Sudoku Solver?") .setCancelable(false) .setNegativeButton("Return", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } } ) .setPositiveButton("Exit", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { System.exit(0); } } ); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } /** * Initialize the activity. */ private void initialize() { Log.i("Initialize", "Initialize Sudoku Board"); GridLayout gridLayout = (GridLayout) findViewById(R.id.cellGrid); gridLayout.setBackground(getDrawable(R.drawable.sudoku_background)); gridLayout.setRowCount(SudokuUtil.TOTAL_ROW_CELLS); gridLayout.setColumnCount(SudokuUtil.TOTAL_COLUMN_CELLS); // dynamically create and set the cells within the grid layout // TODO: Consider dynamic Sudoku Boards _cells = new Cell[SudokuUtil.TOTAL_CELL_INPUTS]; for (int row = 0; row < SudokuUtil.TOTAL_ROW_CELLS; ++row) { for (int col = 0; col < SudokuUtil.TOTAL_COLUMN_CELLS; ++col) { Cell cell = new Cell(this); cell.setParentAtRowAndColumn(gridLayout, row, col); _cells[SudokuUtil.getIndex(row, col)] = cell; } } Log.i("Initialize", "Set Submit Button's listener"); // add the submit button click listener, which will submit the sudoku board Button submitButton = (Button) findViewById(R.id.submitButton); submitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i("Submitting", "Clicked submit button"); submitSudokuBoard(v); } }); // add the reset button click listener, which will reset the sudoku board Button resetButton = (Button) findViewById(R.id.resetButton); resetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i("Submitting", "Clicked submit button"); resetSudokuBoard(); } }); } /** * Create the options menu by inflating a xml defined menu * * @param menu * @return */ @Override public boolean onCreateOptionsMenu(Menu menu) { Log.i("Initialize", "Set menu to menu_my layout"); getMenuInflater().inflate(R.menu.menu_my, menu); return true; } /** * Trigger the options item * * @param item the item that was selected in the options * @return true if it was successful, false otherwise */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.options_about: Log.i("about", "show about fragment"); // show settings fragment DialogFragment newFragment = new SettingsDialogFragment(); newFragment.show(getFragmentManager(), "settings"); return true; case R.id.options_history: Log.i("History", "Clicked history button"); startActivity(new Intent(getApplicationContext(), HistoryActivity.class)); return true; case R.id.options_generate: Log.i("Generating", "Clicked generate button"); generateSudokuBoard(); return true; default: return super.onOptionsItemSelected(item); } } /** * Reset the Sudoku Board. */ private void resetSudokuBoard() { // clear the cell inputs for (int i = 0; i < _cells.length; ++i) { _cells[i].reset(); } } /** * Send the Sudoku Board to the Answer Activity. * * @param view */ private void submitSudokuBoard(View view) { boolean isEmpty = true; // aggregate all the cell data String[] cells = new String[SudokuUtil.TOTAL_CELL_INPUTS]; for (int i = 0; i < _cells.length; ++i) { // extract the cell value from the EditText and store it String cell = _cells[i].getValue(); if (cell.isEmpty()) { // set "0" for empty cells cells[i] = "0"; } else { if (isEmpty) isEmpty = false; cells[i] = cell; } } logInputSudokuBoard(cells); // Prepare the intent to the AnswerActivity Intent intent = new Intent(this, AnswerActivity.class); // pass the cell data with the intent intent.putExtra(EXTRA_CELLS, cells); intent.putExtra(EXTRA_EMPTY_CHECK, isEmpty); startActivity(intent); } private void logInputSudokuBoard(String[] cells) { String logValue = ""; for (int i = 0; i < _cells.length; ++i) { if (i > 0) { // comma separate each item logValue += ", "; } logValue += cells[i]; } // log the submission with the string of cells Log.i("Submission", "Submitted Sudoku Board: " + logValue); } /** * Generate a sample Sudoku Board for testing * * This is a temporary button purely for testing. */ private void generateSudokuBoard() { int[] cells = SudokuUtil.getRandomBoard(); for (int row = 0; row < SudokuUtil.TOTAL_ROW_CELLS; ++row) { for (int col = 0; col < SudokuUtil.TOTAL_COLUMN_CELLS; ++col) { int index = SudokuUtil.getIndex(row, col); Cell cell = _cells[index]; // set value based on the example sudoku board cell.setValue(String.valueOf(cells[index] == SudokuUtil.EMPTY_CELL ? "" : cells[index])); } } } }
package org.springframework.security.oauth2.provider.token; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import java.util.Collections; import java.util.Map; import org.junit.Test; import org.springframework.security.jwt.JwtHelper; import org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.common.util.JsonParser; import org.springframework.security.oauth2.common.util.JsonParserFactory; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.TokenRequest; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; /** * @author Ryan Heaton * @author Dave Syer * */ public class DefaultTokenServicesWithJwtTests extends AbstractDefaultTokenServicesTests { private JwtTokenStore tokenStore; JwtAccessTokenConverter enhancer = new JwtAccessTokenConverter(); @Override protected TokenStore createTokenStore() { tokenStore = new JwtTokenStore(enhancer); return tokenStore; } @Override protected void configureTokenServices(DefaultTokenServices services) throws Exception { enhancer.afterPropertiesSet(); services.setTokenEnhancer(enhancer); super.configureTokenServices(services); } @Test public void testRefreshedTokenHasIdThatMatchesAccessToken() throws Exception { JsonParser parser = JsonParserFactory.create(); OAuth2Authentication authentication = createAuthentication(); OAuth2AccessToken initialToken = getTokenServices().createAccessToken( authentication); ExpiringOAuth2RefreshToken expectedExpiringRefreshToken = (ExpiringOAuth2RefreshToken) initialToken .getRefreshToken(); TokenRequest tokenRequest = new TokenRequest(Collections.singletonMap( "client_id", "id"), "id", null, null); OAuth2AccessToken refreshedAccessToken = getTokenServices().refreshAccessToken( expectedExpiringRefreshToken.getValue(), tokenRequest); Map<String, ?> accessTokenInfo = parser.parseMap(JwtHelper.decode( refreshedAccessToken.getValue()).getClaims()); Map<String, ?> refreshTokenInfo = parser.parseMap(JwtHelper.decode( refreshedAccessToken.getRefreshToken().getValue()).getClaims()); assertEquals("Access token ID does not match refresh token ATI", accessTokenInfo.get(AccessTokenConverter.JTI), refreshTokenInfo.get(AccessTokenConverter.ATI)); assertNotSame("Refresh token re-used", expectedExpiringRefreshToken.getValue(), refreshedAccessToken.getRefreshToken().getValue()); } @Test public void testDoubleRefresh() throws Exception { JsonParser parser = JsonParserFactory.create(); OAuth2Authentication authentication = createAuthentication(); OAuth2AccessToken initialToken = getTokenServices().createAccessToken( authentication); TokenRequest tokenRequest = new TokenRequest(Collections.singletonMap( "client_id", "id"), "id", null, null); OAuth2AccessToken refreshedAccessToken = getTokenServices().refreshAccessToken( initialToken.getRefreshToken().getValue(), tokenRequest); refreshedAccessToken = getTokenServices().refreshAccessToken( refreshedAccessToken.getRefreshToken().getValue(), tokenRequest); Map<String, ?> accessTokenInfo = parser.parseMap(JwtHelper.decode( refreshedAccessToken.getValue()).getClaims()); Map<String, ?> refreshTokenInfo = parser.parseMap(JwtHelper.decode( refreshedAccessToken.getRefreshToken().getValue()).getClaims()); assertEquals("Access token ID does not match refresh token ATI", accessTokenInfo.get(AccessTokenConverter.JTI), refreshTokenInfo.get(AccessTokenConverter.ATI)); } // gh-1109 @Test public void testReuseRefreshToken() { getTokenServices().setReuseRefreshToken(true); OAuth2Authentication authentication = createAuthentication(); OAuth2AccessToken accessToken = getTokenServices().createAccessToken(authentication); ExpiringOAuth2RefreshToken refreshToken = (ExpiringOAuth2RefreshToken) accessToken.getRefreshToken(); TokenRequest tokenRequest = new TokenRequest( Collections.singletonMap("client_id", "id"), "id", null, null); OAuth2AccessToken refreshedAccessToken = getTokenServices().refreshAccessToken( refreshToken.getValue(), tokenRequest); JsonParser parser = JsonParserFactory.create(); Map<String, ?> accessTokenClaims = parser.parseMap( JwtHelper.decode(refreshedAccessToken.getValue()).getClaims()); Map<String, ?> refreshTokenClaims = parser.parseMap( JwtHelper.decode(refreshedAccessToken.getRefreshToken().getValue()).getClaims()); assertEquals("Access token ID (JTI) does not match refresh token ATI", accessTokenClaims.get(AccessTokenConverter.JTI), refreshTokenClaims.get(AccessTokenConverter.ATI)); Map<String, ?> previousRefreshTokenClaims = parser.parseMap( JwtHelper.decode(refreshToken.getValue()).getClaims()); // The ATI claim in the refresh token is a reference to the JTI claim in the access token. // So when an access token is refreshed, the ATI claim in the refresh token needs to be updated // to the JTI claim in the refreshed access token. // Therefore, if DefaultTokenServices.reuseRefreshToken == true, // then all claims in the previous and current refresh token // should be equal minus the ATI claim previousRefreshTokenClaims.remove(AccessTokenConverter.ATI); refreshTokenClaims.remove(AccessTokenConverter.ATI); assertEquals("Refresh token not re-used", previousRefreshTokenClaims, refreshTokenClaims); } }
package tigase.xml; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import tigase.annotations.TODO; /** * <code>Element</code> - basic document tree node implementation. * Supports Java 5.0 generic feature to make it easier to extend this class and * still preserve some useful functionality. Sufficient for simple cases but * probably in the most more advanced cases should be extended with additional * features. Look in API documentation for more details and information about * existing extensions. The most important features apart from abvious tree * implementation are: * <ul> * <li><code>toString()</code> implementation so it can generate valid * <em>XML</em> content from this element and all children.</li> * <li><code>addChild(...)</code>, <code>getChild(childName)</code> supporting * generic types.</li> * <li><code>findChild(childPath)</code> finding child in subtree by given * path to element.</li> * <li><code>getChildCData(childPath)</code>, <code>getAttribute(childPath, * attName)</code> returning element CData from child in subtree by given * path to element.</li> * </ul> * * <p> * Created: Mon Oct 4 17:55:16 2004 * </p> * @author <a href="mailto:artur.hefczyc@gmail.com">Artur Hefczyc</a> * @version $Rev$ */ @TODO(note="Make it a bit lighter.") public class Element implements Comparable<Element>, Cloneable { protected String name = null; protected String cdata = null; protected String xmlns = null; protected HashMap<String, String> attributes = null; protected LinkedList<Element> children = null; @SuppressWarnings({"unchecked"}) public Object clone() { Element result = null; try { result = (Element)super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } // end of try-catch if (attributes != null) { result.attributes = (HashMap<String, String>)attributes.clone(); } else { result.attributes = null; } // end of else if (children != null) { result.setChildren(children); } else { result.children = null; } // end of else return result; } public Element(final Element element) { Element src = (Element) element.clone(); this.attributes = src.attributes; this.name = src.name; this.cdata = src.cdata; this.xmlns = src.xmlns; this.children = src.children; } public Element(final String argName) { setName(argName); } public Element(final String argName, final String argCData) { setName(argName); setCData(argCData); } public Element(final String argName, final String argCData, final StringBuilder[] att_names, final StringBuilder[] att_values) { setName(argName); setCData(argCData); if (att_names != null) { setAttributes(att_names, att_values); } // end of if (att_names != null) } public Element(final String argName, final String argCData, final String[] att_names, final String[] att_values) { setName(argName); setCData(argCData); if (att_names != null) { setAttributes(att_names, att_values); } // end of if (att_names != null) } public List<Element> getChildren() { return children; } public List<Element> getChildren(final String elementPath) { final Element child = findChild(elementPath); return child != null ? child.getChildren() : null; } public void setChildren(final List<Element> children) { this.children = new LinkedList<Element>(); for (Element child: children) { this.children.add((Element)child.clone()); } // end of for (Element child: children) } public void addChildren(final List<Element> children) { if (children == null) { return; } // end of if (children == null) if (this.children == null) { this.children = new LinkedList<Element>(); } // end of if (children == null) synchronized (this.children) { this.children.addAll(children); } } public String toString() { StringBuilder result = new StringBuilder(); result.append("<"+name); if (attributes != null) { for (String key : attributes.keySet()) { result.append(" "+key+"=\""+attributes.get(key)+"\""); } // end of for () } // end of if (attributes != null) final String childrenStr = childrenToString(); if (cdata != null || childrenStr.length() > 0) { result.append(">"); if (cdata != null) { result.append(cdata); } // end of if (cdata != null) result.append(childrenStr); result.append("</"+name+">"); } else { result.append("/>"); } return result.toString(); } public String childrenToString() { StringBuilder result = new StringBuilder(); if (children != null) { synchronized (children) { for (Element child : children) { result.append(child.toString()); } // end of for () } } // end of if (child != null) return result.toString(); } public void addChild(final Element child) { if (children == null) { children = new LinkedList<Element>(); } // end of if (children == null) synchronized (children) { children.add(child); } } public boolean removeChild(final Element child) { boolean res = false; if (children != null) { synchronized (children) { res = children.remove(child); } } // end of if (children == null) return res; } public Element getChild(final String name) { if (children != null) { synchronized (children) { for (Element el : children) { if (el.getName().equals(name)) { return el; } } } } // end of if (children != null) return null; } public Element findChild(final String elementPath) { final StringTokenizer strtok = new StringTokenizer(elementPath, "/", false); if (!strtok.nextToken().equals(getName())) { return null; } // end of if (!strtok.nextToken().equals(child.getName())) Element child = this; while (strtok.hasMoreTokens() && child != null) { child = child.getChild(strtok.nextToken()); } // end of while (strtok.hasMoreTokens()) return child; } public String getChildCData(final String elementPath) { final Element child = findChild(elementPath); return child != null ? child.getCData() : null; } public String getCData(final String elementPath) { final Element child = findChild(elementPath); return child != null ? child.getCData() : null; } /** * Get the Attributes value. * @return the Attributes value. */ public Map<String, String> getAttributes() { return attributes; } /** * Set the Attributes value. * @param newAttributes The new Attributes value. */ public void setAttributes(final Map<String, String> newAttributes) { attributes = new HashMap<String, String>(newAttributes); } public String getAttribute(final String attName) { if (attributes != null) { synchronized (attributes) { return attributes.get(attName); } } // end of if (attributes != null) return null; } public void addAttribute(final String attName, final String attValue) { setAttribute(attName, attValue); } public void addAttributes(Map<String, String> attrs) { attributes.putAll(attrs); } public void setDefXMLNS(final String ns) { xmlns = ns; } public void setXMLNS(final String ns) { setAttribute("xmlns", ns); } public String getXMLNS() { String ns = getAttribute("xmlns"); return ns != null ? ns : xmlns; } public String getXMLNS(final String elementPath) { Element child = findChild(elementPath); return child != null ? child.getXMLNS() : null; } public String getAttribute(final String elementPath, final String att_name) { final Element child = findChild(elementPath); return child != null ? child.getAttribute(att_name) : null; } public void setAttribute(final String elementPath, final String att_name, final String att_value) { final Element child = findChild(elementPath); if (child != null) { child.setAttribute(att_name, att_value); } // end of if (child != null) } public void setAttribute(final String key, final String value) { if (attributes == null) { attributes = new HashMap<String, String>(); } // end of if (attributes == null) synchronized (attributes) { attributes.put(key, value); } } public void setAttributes(final StringBuilder[] names, final StringBuilder[] values) { attributes = new HashMap<String, String>(); synchronized (attributes) { for (int i = 0; i < names.length; i++) { if (names[i] != null) { attributes.put(names[i].toString(), values[i].toString()); } // end of if (names[i] != null) } // end of for (int i = 0; i < names.length; i++) } } public void setAttributes(final String[] names, final String[] values) { attributes = new HashMap<String, String>(); synchronized (attributes) { for (int i = 0; i < names.length; i++) { if (names[i] != null) { attributes.put(names[i], values[i]); } // end of if (names[i] != null) } // end of for (int i = 0; i < names.length; i++) } } /** * Gets the value of name * * @return the value of name */ public String getName() { return this.name; } /** * Sets the value of name * * @param argName Value to assign to this.name */ public void setName(final String argName) { this.name = argName; } /** * Gets the value of cdata * * @return the value of cdata */ public String getCData() { return this.cdata; } /** * Sets the value of cdata * * @param argCData Value to assign to this.cdata */ public void setCData(final String argCData) { this.cdata = argCData; } // Implementation of java.lang.Comparable /** * Method <code>compareTo</code> is used to perform * * @param elem an <code>Object</code> value * @return an <code>int</code> value */ public int compareTo(final Element elem) { return name.compareTo(elem.getName()); } public static void main(final String[] args) { Element elem = new Element("Test", "This is a test", new String[] {"first-name", "last-name"}, new String[] {"Artur", "Hefczyc"}); elem.addChild(new Element("Chile-element")); Element clone = (Element)elem.clone(); System.out.println(clone.toString()); } }// Element
// Triple Play - utilities for use in PlayN-based games package tripleplay.ui; import pythagoras.f.Dimension; import pythagoras.f.IPoint; import pythagoras.f.IRectangle; import pythagoras.f.Point; import pythagoras.f.Rectangle; import playn.core.Connection; import playn.core.Events; import playn.core.GroupLayer; import playn.core.Layer; import playn.core.Pointer; import react.Slot; import tripleplay.ui.Style.HAlign; import tripleplay.ui.Style.VAlign; import static playn.core.PlayN.graphics; /** * Provides a context for popping up a menu. */ public class MenuHost { /** The root layer that will contain all menus that pop up. It should normally be close to the * top of the hierarchy so that it draws on top of everything. */ public final GroupLayer rootLayer; /** The interface we use to create the menu's root and do animation. */ public final Interface iface; /** * An event type for triggering a menu popup. Also acts as a menu constraint so the integrated * host layout can make sure the whole menu is on screen and near to the triggering event * position or element. */ public static class Pop extends Layout.Constraint { /** The element that triggered the popup. {@link #position} is relative to this. */ public final Element<?> trigger; /** The menu to show. */ public final Menu menu; /** The position where the menu should pop up, e.g. a touch event position. Relative to * {@link #trigger}. */ public IPoint position; /** The bounds to confine the menu, in screen coordinates; usually the whole screen. */ public IRectangle bounds; /** Creates a new event and initializes {@link #trigger} and {@link #menu}. */ public Pop (Element<?> trigger, Menu menu) { this.menu = menu; this.trigger = trigger; position = new Point(0, 0); } /** * Causes the menu to handle further events on the given layer. This is usually the layer * handling a pointer start that caused the popup. A listener will be added to the layer * and the menu notified of pointer drag and end events. */ public Pop relayEvents (Layer layer) { _relayTarget = layer; return this; } /** * Positions the menu popup at the given positional event. */ public Pop atEventPos (Events.Position pos) { return atScreenPos(pos.x(), pos.y()); } /** * Positions the menu popup at the given screen position. */ public Pop atScreenPos (float x, float y) { position = new Point(x, y); return this; } /** * Positions the menu horizontally relative to the given layer, with an offset. The * vertical position remains unchanged. */ public Pop atLayerX (Layer layer, float x) { return atScreenPos(Layer.Util.layerToScreen(layer, x, 0).x, position.y()); } /** * Positions the menu vertically relative to the given layer, with an offset. The * horizontal position remains unchanged. */ public Pop atLayerY (Layer layer, float y) { return atScreenPos(position.x(), Layer.Util.layerToScreen(layer, 0, y).y); } /** * Sets the horizontal alignment of the menu relative to the popup position. */ public Pop halign (HAlign halign) { _halign = halign; return this; } /** * Sets the vertical alignment of the menu relative to the popup position. */ public Pop valign (VAlign valign) { _valign = valign; return this; } /** * Positions the right edge of the menu relative to the left edge of the trigger, offset * by the given value. */ public Pop toLeft (float x) { return atLayerX(trigger.layer, x).halign(HAlign.RIGHT); } /** * Positions the left edge of the menu relative to the right edge of the trigger, offset * by the given value. */ public Pop toRight (float x) { return atLayerX(trigger.layer, trigger.size().width() + x).halign(HAlign.LEFT); } /** * Positions the top edge of the menu relative to the top edge of the trigger, offset * by the given value. */ public Pop toTop (float y) { return atLayerY(trigger.layer, y).valign(VAlign.TOP); } /** * Positions the bottom edge of the menu relative to the bottom edge of the trigger, offset * by the given value. */ public Pop toBottom (float y) { return atLayerY(trigger.layer, trigger.size().height() + y).valign(VAlign.BOTTOM); } /** * Flags this {@code Pop} event so that the menu will not be destroyed automatically when * it is deactivated. Returns this instance for chaining. */ public Pop retainMenu () { _retain = true; return this; } /** * Optionally confines the menu area to the given screen area. By default the menu is * confined by the size of the application (see {@link playn.core.Graphics}). */ public Pop inScreenArea (IRectangle area) { bounds = new Rectangle(area); return this; } /** * Optionally confines the menu area to the given element. By default the menu is confined * by the size of the application area (see {@link playn.core.Graphics}). */ public Pop inElement (Element<?> elem) { Point tl = Layer.Util.layerToScreen(elem.layer, 0, 0); Point br = Layer.Util.layerToScreen(elem.layer, elem.size().width(), elem.size().height()); bounds = new Rectangle(tl.x(), tl.y(), br.x() - tl.x(), br.y() - tl.y()); return this; } /** Whether we should keep the menu around (i.e. not destroy it). */ protected boolean _retain; /** The layer that will be sending pointer drag and end events to us. */ protected Layer _relayTarget; protected HAlign _halign = HAlign.LEFT; protected VAlign _valign = VAlign.TOP; } public static Connection relayEvents (Layer from, final Menu to) { return from.addListener(new Pointer.Adapter() { @Override public void onPointerDrag (Pointer.Event e) { to.onPointerDrag(e); } @Override public void onPointerEnd (Pointer.Event e) { to.onPointerEnd(e); } }); } /** * Creates a menu host using the given values. The root layer is set to the layer of the given * root and the stylesheet to its stylesheet. */ public MenuHost (Interface iface, Elements<?> root) { this(iface, root.layer); _stylesheet = root.stylesheet(); } /** * Creates a new menu host using the given values. The stylesheet is set to an empty * one and can be changed via the {@link #setStylesheet(Stylesheet)} method. */ public MenuHost (Interface iface, GroupLayer rootLayer) { this.iface = iface; this.rootLayer = rootLayer; } /** * Sets the stylesheet for menus popped by this host. */ public MenuHost setStylesheet (Stylesheet sheet) { _stylesheet = sheet; return this; } /** * Directs a menu pop signal to {@link #popup(Pop)}. */ public Slot<Pop> onPopup () { return new Slot<Pop>() { @Override public void onEmit (Pop event) { popup(event); } }; } /** * Displays the menu specified by the given pop, incorporating all the configured attributes * therein. */ public void popup (final Pop pop) { // if there is no explicit constraint area requested, use the graphics if (pop.bounds == null) pop.inScreenArea(new Rectangle( 0, 0, graphics().width(), graphics().height())); // set up the menu root final Root menuRoot = iface.createRoot(new RootLayout(), _stylesheet, rootLayer); menuRoot.layer.setDepth(1); menuRoot.layer.setHitTester(null); // get hits from out of bounds menuRoot.add(pop.menu.setConstraint(pop)); menuRoot.pack(); // position the menu Point loc = Layer.Util.screenToLayer(rootLayer, pop.position.x() + pop._halign.offset(menuRoot.size().width(), 0), pop.position.y() + pop._valign.offset(menuRoot.size().height(), 0)); menuRoot.layer.setTranslation(loc.x, loc.y); // set up the activation final Activation activation = new Activation(pop); // connect to deactivation signal and do our cleanup activation.deactivated = pop.menu.deactivated().connect(new Slot<Menu>() { @Override public void onEmit (Menu event) { // check parentage, it's possible the menu has been repopped already if (pop.menu.parent() == menuRoot) { // free the constraint to gc pop.menu.setConstraint(null); // remove or destroy it, depending on the caller's preference if (pop._retain) menuRoot.remove(pop.menu); else menuRoot.destroy(pop.menu); } // clear all connections activation.clear(); // TODO: do we need to stop menu animation here? it should be automatic since // by the time we reach this method, the deactivation animation is complete // always kill off the transient root iface.destroyRoot(menuRoot); // if this was our active menu, clear it if (_active != null && _active.pop.menu == event) _active = null; } }); // close the menu any time the trigger is removed from the hierarchy activation.triggerRemoved = pop.trigger.hierarchyChanged().connect(new Slot<Boolean>() { @Override public void onEmit (Boolean event) { if (!event) pop.menu.deactivate(); } }); // deactivate the old menu if (_active != null) _active.pop.menu.deactivate(); // pass along the animator pop.menu.init(iface.animator()); // activate _active = activation; pop.menu.activate(); } public Menu active () { return _active != null ? _active.pop.menu : null; } /** Simple layout for positioning the menu within the transient {@code Root}. */ protected static class RootLayout extends Layout { @Override public Dimension computeSize (Elements<?> elems, float hintX, float hintY) { return new Dimension(preferredSize(elems.childAt(0), hintX, hintY)); } @Override public void layout (Elements<?> elems, float left, float top, float width, float height) { if (elems.childCount() == 0) return; // get the constraint, it will always be a Pop Pop pop = (Pop)elems.childAt(0).constraint(); // make sure the menu lies inside the requested bounds if the menu doesn't do // that itself if (pop.menu.automaticallyConfine()) { IRectangle bounds = pop.bounds; Point tl = Layer.Util.screenToLayer(elems.layer, bounds.x(), bounds.y()); Point br = Layer.Util.screenToLayer(elems.layer, bounds.x() + bounds.width(), bounds.y() + bounds.height()); // nudge location left = Math.min(Math.max(left, tl.x), br.x - width); top = Math.min(Math.max(top, tl.y), br.y - height); } setBounds(elems.childAt(0), left, top, width, height); } } /** Holds a few variables related to the menu's activation. */ protected static class Activation { /** The configuration of the menu. */ public final Pop pop; /** Connects to the pointer events from the relay. */ public Connection pointerRelay; /** Connection to the trigger's hierarchy change. */ public react.Connection triggerRemoved; /** Connection to the menu's deactivation. */ public react.Connection deactivated; /** Creates a new activation. */ public Activation (Pop pop) { this.pop = pop; // handle pointer events from the relay Layer target = pop._relayTarget; if (target != null) pointerRelay = relayEvents(target, pop.menu); } /** Clears out the connections. */ public void clear () { if (pointerRelay != null) pointerRelay.disconnect(); if (triggerRemoved != null) triggerRemoved.disconnect(); if (deactivated != null) deactivated.disconnect(); pointerRelay = null; triggerRemoved = null; deactivated = null; } } /** The stylesheet used for popped menus. */ protected Stylesheet _stylesheet = Stylesheet.builder().create(); /** Currently active. */ protected Activation _active; }
package com.example.fragment; import android.location.Location; 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.view.ViewGroup; import android.widget.Toast; import com.example.demoaerisproject.R; import com.example.view.TemperatureInfoData; import com.example.view.TemperatureWindowAdapter; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.Marker; import com.hamweather.aeris.communication.Action; import com.hamweather.aeris.communication.AerisCallback; import com.hamweather.aeris.communication.AerisCommunicationTask; import com.hamweather.aeris.communication.AerisRequest; import com.hamweather.aeris.communication.Endpoint; import com.hamweather.aeris.communication.EndpointType; import com.hamweather.aeris.communication.fields.Fields; import com.hamweather.aeris.communication.fields.ObservationFields; import com.hamweather.aeris.communication.parameter.FieldsParameter; import com.hamweather.aeris.communication.parameter.PlaceParameter; import com.hamweather.aeris.location.LocationHelper; import com.hamweather.aeris.maps.AerisMapView; import com.hamweather.aeris.maps.AerisMapView.AerisMapType; import com.hamweather.aeris.maps.MapViewFragment; import com.hamweather.aeris.maps.interfaces.OnAerisMapLongClickListener; import com.hamweather.aeris.maps.interfaces.OnAerisMarkerInfoWindowClickListener; import com.hamweather.aeris.maps.markers.AerisMarker; import com.hamweather.aeris.model.AerisResponse; import com.hamweather.aeris.model.Observation; import com.hamweather.aeris.model.RelativeTo; import com.hamweather.aeris.response.EarthquakesResponse; import com.hamweather.aeris.response.FiresResponse; import com.hamweather.aeris.response.ObservationResponse; import com.hamweather.aeris.response.StormCellResponse; import com.hamweather.aeris.response.StormReportsResponse; public class MapFragment extends MapViewFragment implements OnAerisMapLongClickListener, AerisCallback, OnAerisMarkerInfoWindowClickListener { private LocationHelper locHelper; private Marker marker; private TemperatureWindowAdapter infoAdapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_interactive_maps, container, false); mapView = (AerisMapView) view.findViewById(R.id.aerisfragment_map); mapView.init(savedInstanceState, AerisMapType.GOOGLE); initMap(); setHasOptionsMenu(true); return view; } /** * Inits the map with specific setting */ private void initMap() { locHelper = new LocationHelper(getActivity()); Location myLocation = locHelper.getCurrentLocation(); mapView.moveToLocation(myLocation, 7); mapView.setOnAerisMapLongClickListener(this); // setup the custom info window adapter to use infoAdapter = new TemperatureWindowAdapter(getActivity()); mapView.addWindowInfoAdapter(infoAdapter); // setup doing something when a user presses an info window // from the Aeris Point Data. mapView.setOnAerisWindowClickListener(this); } /* * (non-Javadoc) * * @see android.app.Fragment#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.menu_weather_layers) { mapView.startAerisMapOptionsActivity(getActivity()); return false; } else { return super.onOptionsItemSelected(item); } } @Override public void onResume() { super.onResume(); } /* * (non-Javadoc) * * @see android.app.Fragment#onCreateOptionsMenu(android.view.Menu, * android.view.MenuInflater) */ @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_maps_fragment, menu); super.onCreateOptionsMenu(menu, inflater); } /* * (non-Javadoc) * * @see com.hamweather.aeris.maps.AerisMapView.OnAerisMapLongClickListener# * onMapLongClick(double, double) */ @Override public void onMapLongClick(double lat, double longitude) { AerisRequest request = new AerisRequest(new Endpoint( EndpointType.OBSERVATIONS), Action.CLOSEST, new PlaceParameter( lat, longitude), FieldsParameter.initWith( ObservationFields.ICON, ObservationFields.TEMP_C, ObservationFields.TEMP_F, Fields.RELATIVE_TO)); AerisCommunicationTask task = new AerisCommunicationTask(getActivity(), this, request); task.execute(); } /* * (non-Javadoc) * * @see * com.hamweather.aeris.communication.AerisCallback#onResult(com.hamweather * .aeris.communication.EndpointType, * com.hamweather.aeris.model.AerisResponse) */ @Override public void onResult(EndpointType type, AerisResponse response) { if (type == EndpointType.OBSERVATIONS) { if (response.isSuccessfulWithResponses()) { ObservationResponse obResponse = new ObservationResponse( response.getFirstResponse()); Observation ob = obResponse.getObservation(); RelativeTo relativeTo = obResponse.getRelativeTo(); if (marker != null) { marker.remove(); } TemperatureInfoData data = new TemperatureInfoData(ob.icon, String.valueOf(ob.tempF)); marker = infoAdapter.addGoogleMarker(mapView.getMap(), relativeTo.lat, relativeTo.lon, BitmapDescriptorFactory .fromResource(R.drawable.map_indicator_blank), data); marker.showInfoWindow(); } } } @Override public void earthquakeWindowPressed(EarthquakesResponse response, AerisMarker marker) { // do something with the response data. Toast.makeText(getActivity(), "Earthquake pressed!", Toast.LENGTH_SHORT) .show(); } @Override public void stormReportsWindowPressed(StormReportsResponse response, AerisMarker marker) { // do something with the response data. Toast.makeText(getActivity(), "Storm Report pressed!", Toast.LENGTH_SHORT).show(); } @Override public void stormCellsWindowPressed(StormCellResponse response, AerisMarker marker) { // do something with the response data. Toast.makeText(getActivity(), "Storm Cell pressed!", Toast.LENGTH_SHORT) .show(); } @Override public void wildfireWindowPressed(FiresResponse response, AerisMarker marker) { // do something with the response data. Toast.makeText(getActivity(), "Wildfire pressed!", Toast.LENGTH_SHORT) .show(); } }
package wordcram; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.geom.GeneralPath; import processing.core.PGraphics; import processing.awt.PGraphicsJava2D; class ProcessingWordRenderer implements WordRenderer { PGraphics destination; ProcessingWordRenderer(PGraphics destination) { this.destination = destination; } public int getWidth() { return destination.width; } public int getHeight() { return destination.height; } public void drawWord(EngineWord word, Color color) { GeneralPath path2d = new GeneralPath(word.getShape()); // Graphics2D g2 = (Graphics2D)destination.image.getGraphics(); Graphics2D g2 = ((PGraphicsJava2D)destination).g2; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setPaint(color); g2.fill(path2d); } public void finish() {} }
package au.edu.unimelb.boldapp.sync; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.SocketException; import java.util.Arrays; import java.util.List; import android.util.Log; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPConnectionClosedException; /** * FTP client that allows the application to sync it's data with a server. * * @author Oliver Adams <oliver.adams@gmail.com> * @author Florian Hanke <florian.hanke@gmail.com> */ public class Client { /** * Set up the working directory for the client. */ public void setClientBaseDir(String clientBaseDir) { this.clientBaseDir = clientBaseDir; } /** * Set up the working directory for the server. */ public void setServerBaseDir(String serverBaseDir) { this.serverBaseDir = serverBaseDir; } /** * Standard constructor */ public Client() { apacheClient = new org.apache.commons.net.ftp.FTPClient(); } /** * Login to a server. * * @param serverURI The server URI. * @param username The username. * @param password The password. * * @return true if the login was successful; false otherwise. */ public boolean login(String serverURI, String username, String password) { boolean result = false; if (!apacheClient.isConnected()) { try { apacheClient.connect(serverURI); } catch (SocketException e) { Log.i("sync", "socketexception"); return false; } catch (IOException e) { Log.i("sync", "firstIOException"); return false; } } if (!loggedIn) { try { result = apacheClient.login(username, password); loggedIn = result; } catch (IOException e) { Log.i("sync", "secondIOException"); return false; } } try { // This code cannot be run before logging in, although no // documentation ever says that. result = apacheClient.setFileType(FTP.BINARY_FILE_TYPE); if (!result) { Log.i("sync", "setFileType returned false"); return false; } } catch (IOException e) { //Log.i("sync", "thirdIOException"); return false; } // Change to appropriate working directory if (loggedIn) { try { apacheClient.makeDirectory(serverBaseDir); result = cdServerBaseDir(); //result = true; //Log.i("sync", "cdServerBaseDir result: " + result); } catch (IOException e ) { Log.i("sync", "fourthIOException"); return false; } } //Log.i("sync", "final"); return result; } /** * Logout of a server. */ public boolean logout() { if (apacheClient == null) { return false; } if (loggedIn) { try { boolean result; result = apacheClient.logout(); loggedIn = !result; return result; } catch (IOException e) { return false; } } return false; } /** * Sync the client with the server. * * @return true if completely successful; false otherwise. */ public boolean sync() { boolean pushResult = push(); boolean pullResult = pull(); Log.i("zxcv", "pushResult: " + pushResult); Log.i("zxcv", "pullResult: " + pullResult); return pushResult && pullResult; } /** * Push files to server that are on the client but not the server. * * @return true if successful; false otherwise. */ public boolean push() { return pushDirectory("."); } /** * Pull file from the server that are on the server but not on the client. * * @return true if successful; false otherwise. */ public boolean pull() { return pullDirectory("."); } /** * Recursively push the directory to server. * * @param directoryPath the relative path from the base directory */ public boolean pushDirectory(String directoryPath) { // Get the specified client side directory. File clientDir = new File(clientBaseDir + directoryPath); if (!clientDir.isDirectory()) { return false; } // Attempt to make the directory on the server side and then change // into it. try { apacheClient.makeDirectory( serverBaseDir + directoryPath); apacheClient.changeWorkingDirectory( serverBaseDir + directoryPath); } catch (IOException e) { return false; } try { List<String> clientFilenames = Arrays.asList(clientDir.list()); List<String> serverFilenames = Arrays.asList( apacheClient.listNames()); File file = null; Boolean result = null; for (String filename : clientFilenames) { file = new File(clientDir.getPath() + "/" + filename); if (!file.getName().endsWith(".inprogress")) { if (!file.isDirectory()) { if (!serverFilenames.contains(filename)) { result = pushFile(directoryPath, file); if (!result) { return false; } } } else { apacheClient.makeDirectory(filename); result = pushDirectory(directoryPath + "/" + filename); apacheClient.changeWorkingDirectory( serverBaseDir + directoryPath); if (!result) { return false; } } } } } catch (IOException e) { e.printStackTrace(); return false; } return true; } /** * Push an individual file to the server. * * @param file The file to be pushed. * @return true if successful; false otherwise. */ public boolean pushFile(String directoryPath, File file) { boolean result = false; try { InputStream stream = new FileInputStream(file); result = apacheClient.storeFile( serverBaseDir + directoryPath + "/" + file.getName() + ".inprogress", stream); stream.close(); apacheClient.rename( serverBaseDir + directoryPath + "/" + file.getName() + ".inprogress", serverBaseDir + directoryPath + "/" + file.getName()); } catch (IOException e) { return false; } return result; } /** * Pull an individual file from the server. * * @param file The file to be pulled. * @return true if successful; false otherwise. */ public boolean pullFile(String directoryPath, File file) { Log.i("zxcv", "pullFile: " + directoryPath + " " + file.getName()); boolean result = false; try { File inProgressFile = new File(file.getPath() + ".inprogress"); /*clientBaseDir + directoryPath + "/" + file.getName() + ".inprogress");*/ Log.i("zxcv", "inprogressfilename " + inProgressFile.getPath()); OutputStream stream = new FileOutputStream(inProgressFile); result = apacheClient.retrieveFile( serverBaseDir + directoryPath + "/" + file.getName(), stream); stream.close(); Log.i("zxcv", "blah: " + inProgressFile.getName() + " " + result); inProgressFile.renameTo(file); } catch (IOException e) { Log.e("zxcv", "borg" , e); return false; } return result; } /** * Recursively pull the directory from the server. * * @param directoryPath the relative path from the base directory */ public boolean pullDirectory(String directoryPath) { // Attempt to change to the directory on the server side. try { boolean result; result = apacheClient.changeWorkingDirectory( serverBaseDir + directoryPath); if (!result) { return false; } } catch (IOException e) { return false; } File clientDir = new File(clientBaseDir + directoryPath); clientDir.mkdirs(); try { List<String> clientFilenames = Arrays.asList(clientDir.list()); List<FTPFile> serverFiles = Arrays.asList( apacheClient.listFiles()); File file = null; OutputStream stream = null; Boolean result = null; for (FTPFile serverFile : serverFiles) { file = new File( clientBaseDir + directoryPath + "/" + serverFile.getName()); if (!file.getName().endsWith(".inprogress")) { if (serverFile.isDirectory()) { file.mkdirs(); result = pullDirectory( directoryPath + "/" + serverFile.getName()); if (!result) { return false; } } else { if (!clientFilenames.contains(serverFile.getName())) { result = pullFile(directoryPath, file); if (!result) { return false; } } } } } } catch (IOException e) { e.printStackTrace(); return false; } return true; } /** * Change the working directory of the apache client. * * @return true if successful; false otherwise. */ public boolean cdServerBaseDir() { try { return apacheClient.changeWorkingDirectory(serverBaseDir); } catch (IOException e) { return false; } } /** * Finds the first writable directory on the server. * * @return the first writable directory on the server. */ /* public String findServerBaseDir() { return findWritableDir("/"); } private String findWritableDir(String startPath) { try { apacheClient.changeWorkingDirectory(startPath); List<FTPFile> directories; String writable; if (apacheClient.makeDirectory("bold") == false) { directories = Arrays.asList(apacheClient.listDirectories()); for (FTPFile dir : directories) { System.out.println(dir.getName()); System.out.println(startPath + dir.getName()); writable = findWritableDir(startPath + dir.getName()); if (writable != null) { return writable; } } } else { return apacheClient.printWorkingDirectory(); } } catch (IOException e) { return null; } return null; } */ /** * The Apache FTPClient used by this FTPClient. */ private org.apache.commons.net.ftp.FTPClient apacheClient; /** * Whether the client is logged in or not. */ private boolean loggedIn = false; /** * The path to the client's working directory. */ private String clientBaseDir; /** * The path to the working directory. */ private String serverBaseDir; }
package jade.core; import jade.lang.acl.ACLMessage; import jade.util.leap.List; import jade.util.leap.Iterator; import jade.util.leap.Properties; import jade.util.Logger; import jade.security.AuthException; //#MIDP_EXCLUDE_BEGIN import jade.core.behaviours.Behaviour; import jade.security.*; import jade.security.dummy.*; //#MIDP_EXCLUDE_END import java.util.Hashtable; import java.util.Vector; import java.util.Enumeration; /** @author Giovanni Caire - TILAB */ class FrontEndContainer implements FrontEnd, AgentToolkit, Runnable { public static final String CONN_MGR_CLASS_KEY = "connection-manager"; private static final String CONN_MGR_CLASS_DEFAULT = "jade.imtp.leap.JICP.FrontEndDispatcher"; // The table of local agents private Hashtable localAgents = new Hashtable(1); // The ID of this container private ContainerID myId; // The name of this container // The name of the platform this container belongs to // The addresses of the platform this container belongs to private String[] platformInfo; // The AID of the AMS private AID amsAID; // The AID of the default DF private AID dfAID; // The buffer of messages to be sent to the BackEnd private Vector pending = new Vector(4); // The BackEnd this FrontEndContainer is connected to private BackEnd myBackEnd; // The manager of the connection with the BackEnd private FEConnectionManager myConnectionManager; // The configuration properties for this FrontEndContainer private Properties configProperties; // Flag indicating that the shutdown procedure is in place private boolean exiting = false; //#MIDP_EXCLUDE_BEGIN private Authority authority = new DummyAuthority(); //#MIDP_EXCLUDE_END /** Construct a FrontEndContainer and connect to the BackEnd. */ FrontEndContainer(Properties p) { configProperties = p; // Start the therad for asynchronous message delivery Thread t = new Thread(this); t.start(); // Connect to the BackEnd try { String connMgrClass = configProperties.getProperty(CONN_MGR_CLASS_KEY); if (connMgrClass == null) { connMgrClass = CONN_MGR_CLASS_DEFAULT; } myConnectionManager = (FEConnectionManager) Class.forName(connMgrClass).newInstance(); myBackEnd = myConnectionManager.getBackEnd(this, configProperties); } catch (IMTPException imtpe) { Logger.println("IMTP error. "+imtpe); imtpe.printStackTrace(); MicroRuntime.handleTermination(true); return; } catch (Exception e) { Logger.println("Unexpected error. "+e); e.printStackTrace(); MicroRuntime.handleTermination(true); return; } // Lanch agents String agents = configProperties.getProperty(MicroRuntime.AGENTS_KEY); try { // Create all agents without starting them List specs = Specifier.parseSpecifierList(agents); Iterator it = specs.iterator(); while (it.hasNext()) { Specifier s = (Specifier) it.next(); try { initAgent(s.getName(), s.getClassName(), s.getArgs()); } catch (Exception e) { Logger.println("Exception creating new agent. "+e); } } // Start agents only after they are all there synchronized (this) { Enumeration e = localAgents.keys(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); AID id = new AID(name, AID.ISLOCALNAME); Agent a = (Agent) localAgents.get(name); a.powerUp(id, new Thread(a)); } } } catch (Exception e1) { Logger.println("Exception parsing agent specifiers. "+e1); e1.printStackTrace(); } } // FrontEnd interface implementation /** Request the FrontEnd container to create a new agent. @param name The name of the new agent. @param className The class of the new agent. @param args The arguments to be passed to the new agent. */ public final void createAgent(String name, String className, String[] args) throws IMTPException { try { initAgent(name, className, (Object[]) args); AID id = new AID(name, AID.ISLOCALNAME); Agent a = (Agent) localAgents.get(name); a.powerUp(id, new Thread(a)); //#NODEBUG_EXCLUDE_BEGIN //java.lang.Runtime rt = java.lang.Runtime.getRuntime(); //rt.gc(); //System.out.println("Used memory = "+((rt.totalMemory()-rt.freeMemory())/1024)+"K"); //#NODEBUG_EXCLUDE_END } catch (Exception e) { String msg = "Exception creating new agent. "; Logger.println(msg+e); throw new IMTPException(msg, e); } } /** Request the FrontEnd container to kill an agent. @param name The name of the agent to kill. */ public final void killAgent(String name) throws NotFoundException, IMTPException { Agent agent = (Agent) localAgents.get(name); if(agent == null) { throw new NotFoundException("KillAgent failed to find " + name); } agent.doDelete(); // Note that the agent will be removed from the local table when its // handleEnd() is called. } /** Request the FrontEnd container to suspend an agent. @param name The name of the agent to suspend. */ public final void suspendAgent(String name) throws NotFoundException, IMTPException { Agent agent = (Agent) localAgents.get(name); if(agent == null) { throw new NotFoundException("SuspendAgent failed to find " + name); } agent.doSuspend(); } /** Request the FrontEnd container to resume an agent. @param name The name of the agent to resume. */ public final void resumeAgent(String name) throws NotFoundException, IMTPException { Agent agent = (Agent) localAgents.get(name); if(agent == null) { throw new NotFoundException("ResumeAgent failed to find " + name); } agent.doActivate(); } /** Pass an ACLMessage to the FrontEnd for posting. @param msg The message to be posted. @param sender The name of the receiver agent. */ public final void messageIn(ACLMessage msg, String receiver) throws NotFoundException, IMTPException { if (receiver != null) { Agent agent = (Agent) localAgents.get(receiver); if(agent == null) { throw new NotFoundException("Receiver "+receiver+" not found"); } agent.postMessage(msg); } } /** Request the FrontEnd container to exit. */ public final void exit(boolean self) throws IMTPException { if (!exiting) { exiting = true; Logger.println("Container shut down activated"); // Kill all agents synchronized (this) { Enumeration e = localAgents.elements(); while (e.hasMoreElements()) { // Kill agent and wait for its termination Agent a = (Agent) e.nextElement(); a.doDelete(); a.join(); a.resetToolkit(); } localAgents.clear(); } // Shut down the connection with the BackEnd. The BackEnd will // exit and deregister with the main myConnectionManager.shutdown(); // Notify the JADE Runtime that the container has terminated execution MicroRuntime.handleTermination(self); } } // AgentToolkit interface implementation public final Location here() { return myId; } public final void handleStart(String localName, Agent instance) { // Will never be called --> just do nothing } public final void handleEnd(AID agentID) { if (!exiting) { // If this agent is ending because the container is exiting // just do nothing. The BackEnd will notify the main. try { String name = agentID.getLocalName(); synchronized (this) { localAgents.remove(name); } myBackEnd.deadAgent(name); // If there are no more agents and the exitwhenempty option // is set, activate shutdown if ("true".equals(configProperties.getProperty("exitwhenempty"))) { if (localAgents.isEmpty()) { exit(true); } } } catch(IMTPException re) { Logger.println(re.toString()); } } } public final void handleChangedAgentState(AID agentID, AgentState from, AgentState to) { // FIXME: This should call myBackEnd.suspendedAgent()/resumedAgent() } public final void handleSend(ACLMessage msg, AID sender) throws AuthException { Iterator it = msg.getAllIntendedReceiver(); // If some receiver is local --> directly post the message int remoteCnt = 0; while (it.hasNext()) { remoteCnt++; AID id = (AID) it.next(); Agent a = (Agent) localAgents.get(id.getLocalName()); if (a != null) { ACLMessage m = (ACLMessage) msg.clone(); a.postMessage(m); remoteCnt } } // If some receiver is remote --> pass the message to the BackEnd if (remoteCnt > 0) { post(msg, sender.getLocalName()); } } public final void setPlatformAddresses(AID id) { id.clearAllAddresses(); for (int i = 2; i < platformInfo.length; ++i) { id.addAddresses(platformInfo[i]); } } public final AID getAMS() { return amsAID; } public final AID getDefaultDF() { return dfAID; } public String getProperty(String key, String aDefault) { String ret = configProperties.getProperty(key); return (ret != null ? ret : aDefault); } //#MIDP_EXCLUDE_BEGIN public void handleMove(AID agentID, Location where) throws AuthException, IMTPException, NotFoundException { } public void handleClone(AID agentID, Location where, String newName) throws AuthException, IMTPException, NotFoundException { } public void handlePosted(AID agentID, ACLMessage msg) throws AuthException { } public void handleReceived(AID agentID, ACLMessage msg) throws AuthException { } public void handleBehaviourAdded(AID agentID, Behaviour b) { } public void handleBehaviourRemoved(AID agentID, Behaviour b) { } public void handleChangeBehaviourState(AID agentID, Behaviour b, String from, String to) { } public void handleChangedAgentPrincipal(AID agentID, AgentPrincipal from, CertificateFolder certs) { } public Authority getAuthority() { return authority; } //#MIDP_EXCLUDE_END // Private methods private final void initInfo(String[] info) { myId = new ContainerID(info[0], null); AID.setPlatformID(info[1]); platformInfo = info; amsAID = new AID("ams", AID.ISLOCALNAME); setPlatformAddresses(amsAID); dfAID = new AID("df", AID.ISLOCALNAME); setPlatformAddresses(dfAID); } private final void initAgent(String name, String className, Object[] args) throws Exception { synchronized (this) { Agent previous = null; try { // Create the new agent and add it to the local agents table Agent agent = (Agent) Class.forName(className).newInstance(); agent.setArguments(args); agent.setToolkit(this); previous = (Agent) localAgents.put(name, agent); // Notify the BackEnd (get back platform info if this is the first agent) String[] info = myBackEnd.bornAgent(name); if (info != null) { initInfo(info); } } catch (Exception e) { // If an exception occurs, roll back and restore the previous agent if any. localAgents.remove(name); if(previous != null) { localAgents.put(name, previous); } // Re-throw the exception throw e; } } } private void post(ACLMessage msg, String sender) { synchronized(pending) { pending.addElement(msg.clone()); pending.addElement(sender); pending.notifyAll(); } } public void run() { ACLMessage msg = null; String sender = null; while (true) { synchronized(pending) { while (pending.size() == 0) { try { pending.wait(); } catch (InterruptedException ie) { // Should never happen Logger.println(ie.toString()); } } msg = (ACLMessage) pending.elementAt(0); sender = (String) pending.elementAt(1); pending.removeElementAt(1); pending.removeElementAt(0); } try { myBackEnd.messageOut(msg, sender); } catch (Exception e) { // Should never happen. Note that "NotFound" here is referred // to the sender. Logger.println(e.toString()); } } } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // * Neither the name of the <organization> nor the // names of its contributors may be used to endorse or promote products // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package wyil.transforms; import static wyil.util.SyntaxError.syntaxError; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.HashSet; import wyil.ModuleLoader; import wyil.lang.*; import wyil.lang.Code.*; import wyil.util.*; import wyil.util.dfa.*; import static wyil.lang.Block.*; /** * <p> * The type propagation stage propagates type information in a flow-sensitive * fashion from declared parameter and return types through assigned * expressions, to determine types for all intermediate expressions and * variables. In some cases, this process will actually update the underlying * expressions to reflect the correct operator. For example, an expression * <code>a+b</code> will always initially be parsed as a CExpr.BinOp with ADD * operator. However, if type propagation determines that <code>a</code> and * <code>b</code> have set type, then the operator will be updated to a UNION. * </p> * <p> * <b<Note:</b> currently, this stage does not propagate through type definitions. * </p> * * @author djp * */ public class TypePropagation extends ForwardFlowAnalysis<TypePropagation.Env> { public TypePropagation(ModuleLoader loader) { super(loader); } public Module.TypeDef propagate(Module.TypeDef type) { return type; } public Module.ConstDef propagate(Module.ConstDef def) { return def; } public Env initialStore() { Env environment = new Env(); if(method.type().receiver() != null) { environment.add(method.type().receiver()); } List<Type> paramTypes = method.type().params(); for (int i = 0; i != paramTypes.size(); ++i) { Type t = paramTypes.get(i); environment.add(t); if (method.type().receiver() == null && Type.isSubtype(Type.T_PROCESS(Type.T_ANY), t)) { // FIXME: add source information syntaxError("function argument cannot have process type", filename, methodCase); } } return environment; } public Module.Case propagate(Module.Case mcase) { this.methodCase = mcase; this.stores = new HashMap<String,Env>(); Env environment = initialStore(); Block body = propagate(mcase.body(), environment).first(); return new Module.Case(body,mcase.attributes()); } protected Pair<Entry, Env> propagate(Entry entry, Env environment) { Code code = entry.code; environment = (Env) environment.clone(); if(code instanceof Assert) { code = infer((Assert)code,entry,environment); } else if(code instanceof BinOp) { code = infer((BinOp)code,entry,environment); } else if(code instanceof Convert) { code = infer((Convert)code,entry,environment); } else if(code instanceof Const) { code = infer((Const)code,entry,environment); } else if(code instanceof Debug) { code = infer((Debug)code,entry,environment); } else if(code instanceof ExternJvm) { return new Pair(entry,environment); } else if(code instanceof Fail) { code = infer((Fail)code,entry,environment); } else if(code instanceof FieldLoad) { code = infer((FieldLoad)code,entry,environment); } else if(code instanceof FieldStore) { code = infer((FieldStore)code,entry,environment); } else if(code instanceof IndirectInvoke) { code = infer((IndirectInvoke)code,entry,environment); } else if(code instanceof IndirectSend) { code = infer((IndirectSend)code,entry,environment); } else if(code instanceof Invoke) { code = infer((Invoke)code,entry,environment); } else if(code instanceof Label) { return new Pair(entry,environment); } else if(code instanceof ListLoad) { code = infer((ListLoad)code,entry,environment); } else if(code instanceof ListStore) { code = infer((ListStore)code,entry,environment); } else if(code instanceof Load) { code = infer((Load)code,entry,environment); } else if(code instanceof Return) { code = infer((Return)code,entry,environment); } else if(code instanceof UnOp) { code = infer((UnOp)code,entry,environment); } else { syntaxError("Need to finish type inference",filename,entry); return null; } } protected Code infer(Code.Assert code, Entry stmt, Env environment) { return null; } protected Code infer(BinOp v, Entry stmt, Env environment) { Type lhs = environment.pop(); Type rhs = environment.pop(); Type lub = Type.leastUpperBound(lhs,rhs); Code.BOp bop = v.bop; if(Type.isSubtype(Type.T_LIST(Type.T_ANY),lub)) { switch(v.bop) { case APPEND: case ADD: bop = Code.BOp.APPEND; break; default: syntaxError("Invalid operation on lists",filename,stmt); } } else if(Type.isSubtype(Type.T_SET(Type.T_ANY),lub)) { switch(v.bop) { case ADD: case UNION: bop = Code.BOp.UNION; break; case DIFFERENCE: case SUB: bop = Code.BOp.DIFFERENCE; break; case INTERSECT: break; default: syntaxError("Invalid operation on sets: " + bop,filename,stmt); } } else { // FIXME: more cases, including elem of checkIsSubtype(Type.T_REAL,lub,stmt); } return Code.BinOp(lub,bop); } protected Code infer(Code.Convert code, Entry stmt, Env environment) { Type t = environment.pop(); checkIsSubtype(code.to,t,stmt); environment.push(code.to); return null; } protected Code infer(Code.Const code, Entry stmt, Env environment) { return null; } protected Code infer(Code.Debug code, Entry stmt, Env environment) { CExpr rhs = infer(code.rhs,stmt, environment); checkIsSubtype(Type.T_LIST(Type.T_INT),rhs.type(),stmt); return new Code.Debug(rhs); } protected Code infer(Code.Fail code, Entry stmt, Env environment) { return null; } protected Code infer(FieldLoad e, Entry stmt, Env environment) { CExpr lhs = infer(e.lhs,stmt,environment); // FIXME: would help to have effective process type if(lhs.type() instanceof Type.Process) { // this indicates a process dereference lhs = CExpr.UNOP(UOP.PROCESSACCESS,lhs); } Type.Record ett = Type.effectiveRecordType(lhs.type()); if (ett == null) { syntaxError("tuple type required, got: " + lhs.type(), filename, stmt); } Type ft = ett.fields().get(e.field); if (ft == null) { syntaxError("type has no field named " + e.field, filename, stmt); } return CExpr.RECORDACCESS(lhs, e.field); } protected Code infer(FieldStore e, Entry stmt, Env environment) { return null; } protected Code infer(IndirectInvoke e, Entry stmt, Env environment) { return null; } protected Code infer(IndirectSend e, Entry stmt, Env environment) { return null; } protected Code infer(Invoke ivk, Entry stmt, Env environment) { ArrayList<CExpr> args = new ArrayList<CExpr>(); ArrayList<Type> types = new ArrayList<Type>(); CExpr receiver = ivk.receiver; Type.Process receiverT = null; if(receiver != null) { receiver = infer(receiver, stmt, environment); receiverT = checkType(receiver.type(),Type.Process.class,stmt); } for (CExpr arg : ivk.args) { arg = infer(arg, stmt, environment); args.add(arg); types.add(arg.type()); } try { Type.Fun funtype = bindFunction(ivk.name, receiverT, types, stmt); return CExpr.DIRECTINVOKE(funtype, ivk.name, ivk.caseNum, receiver, ivk.synchronous, args); } catch (ResolveError ex) { syntaxError(ex.getMessage(), filename, stmt); return null; // unreachable } } protected Code infer(IndirectInvoke ivk, Entry stmt, HashMap<String,Type> environment) { ArrayList<CExpr> args = new ArrayList<CExpr>(); CExpr receiver = ivk.receiver; CExpr target = ivk.target; Type.Process receiverT = null; if(receiver != null) { receiver = infer(receiver, stmt, environment); receiverT = checkType(receiver.type(),Type.Process.class,stmt); } target = infer(target, stmt, environment); checkType(target.type(),Type.Fun.class,stmt); for (CExpr arg : ivk.args) { arg = infer(arg, stmt, environment); args.add(arg); } return CExpr.INDIRECTINVOKE(target, receiver, args); } protected Code infer(ListLoad e, Entry stmt, Env environment) { CExpr src = infer(e.src,stmt,environment); CExpr idx = infer(e.index,stmt,environment); if(Type.isSubtype(Type.T_DICTIONARY(Type.T_ANY, Type.T_ANY),src.type())) { // this indicates a dictionary access, rather than a list access // FIXME: need "effective dictionary type" or similar here Type.Dictionary dict = (Type.Dictionary) src.type(); checkIsSubtype(dict.key(),idx.type(),stmt); // OK, it's a hit return CExpr.LISTACCESS(src,idx); } else { checkIsSubtype(Type.T_LIST(Type.T_ANY),src.type(),stmt); checkIsSubtype(Type.T_INT,idx.type(),stmt); return CExpr.LISTACCESS(src,idx); } } protected Code infer(ListStore e, Entry stmt, Env environment) { return null; } protected Code infer(Load e, Entry stmt, Env environment) { e = Code.Load(environment.get(e.slot), e.slot); environment.push(e.type); return e; } protected CExpr infer(NewRecord e, Entry stmt, HashMap<String,Type> environment) { HashMap<String, CExpr> args = new HashMap<String, CExpr>(); for (Map.Entry<String, CExpr> v : e.values.entrySet()) { args.put(v.getKey(), infer(v.getValue(), stmt, environment)); } return CExpr.RECORD(args); } protected CExpr infer(NewDict e, Entry stmt, HashMap<String,Type> environment) { HashSet<Pair<CExpr,CExpr>> args = new HashSet(); for (Pair<CExpr,CExpr> v : e.values) { CExpr key = infer(v.first(), stmt, environment); CExpr value = infer(v.second(), stmt, environment); args.add(new Pair<CExpr,CExpr>(key,value)); } return CExpr.DICTIONARY(args); } protected Code infer(Store e, Entry stmt, Env environment) { e = Code.Store(environment.pop(), e.slot); environment.set(e.slot, e.type); return e; } protected Code infer(Code.Return code, Entry stmt, Env environment) { CExpr rhs = code.rhs; Type ret_t = method.type().ret(); if(rhs != null) { if(ret_t == Type.T_VOID) { syntaxError( "cannot return value from method with void return type", filename, stmt); } rhs = infer(rhs,stmt,environment); checkIsSubtype(ret_t,rhs.type(),stmt); } else if(ret_t != Type.T_VOID) { syntaxError( "missing return value",filename, stmt); } return new Code.Return(rhs); } protected Code infer(UnOp v, Entry stmt, Env environment) { CExpr rhs = infer(v.rhs, stmt, environment); Type rhs_t = rhs.type(); switch(v.op) { case NEG: checkIsSubtype(Type.T_REAL,rhs_t,stmt); return CExpr.UNOP(v.op,rhs); case LENGTHOF: if(rhs_t instanceof Type.List || rhs_t instanceof Type.Set) { return CExpr.UNOP(v.op,rhs); } else { syntaxError("expected list or set, found " + rhs_t,filename,stmt); } case PROCESSACCESS: checkIsSubtype(Type.T_PROCESS(Type.T_ANY),rhs_t,stmt); return CExpr.UNOP(v.op,rhs); case PROCESSSPAWN: return CExpr.UNOP(v.op,rhs); } syntaxError("unknown unary operation: " + v.op,filename,stmt); return null; } /* protected Pair<Entry, Env> infer(Code.Assign code, Entry stmt, Env environment) { environment = new Env(environment); CExpr.LVal lhs = null; CExpr rhs; if(code.lhs != null) { if(code.lhs instanceof CExpr.LVar) { CExpr.LVar lv = (CExpr.LVar) code.lhs; lhs = lv; // Simple test if(lv.name().equals("this")) { syntaxError("cannot assign to variable this",filename,stmt); } } else { lhs = (CExpr.LVal) infer(code.lhs,stmt,environment); } // Update the type of the lhs rhs = infer(code.rhs,stmt,environment); lhs = (CExpr.LVal) typeInference(lhs,rhs.type(),environment); } else { // I by pass infer(CExpr) here, since that method requires all // expressions to have a non-void return type. if(code.rhs instanceof DirectInvoke) { rhs = infer((DirectInvoke)code.rhs,stmt,environment); } else if(code.rhs instanceof IndirectInvoke) { rhs = infer((IndirectInvoke)code.rhs,stmt,environment); } else { syntaxError("invalid expression",filename,stmt); return null; // dead code } } stmt = new Entry(new Code.Assign(lhs, rhs), stmt.attributes()); return new Pair<Entry,Env>(stmt,environment); } protected CExpr typeInference(CExpr lhs, Type type, Env environment) { if(lhs instanceof Variable) { Variable v = (Variable) lhs; environment.put(v.name, type); return CExpr.VAR(type,v.name); } else if(lhs instanceof Register) { Register v = (Register) lhs; environment.put("%" + v.index, type); return CExpr.REG(type,v.index); } else if(lhs instanceof ListAccess) { ListAccess la = (ListAccess) lhs; Type.List la_src_t = Type.effectiveListType(la.src.type()); if(la_src_t instanceof Type.List) { Type elem_t = Type.leastUpperBound(la_src_t.element(),type); lhs = typeInference(la.src,Type.T_LIST(elem_t),environment); return CExpr.LISTACCESS(lhs, la.index); } else { Type.Dictionary tl = (Type.Dictionary) Type.effectiveDictionaryType(la.src.type()); Type key_t = Type.leastUpperBound(tl.key(),la.index.type()); Type val_t = Type.leastUpperBound(tl.value(),type); lhs = typeInference(la.src,Type.T_DICTIONARY(key_t,val_t),environment); return CExpr.LISTACCESS(lhs, la.index); } } else if(lhs instanceof RecordAccess) { RecordAccess r = (RecordAccess) lhs; Type lhs_t = updateRecordFieldType(r.lhs.type(),r.field,type); lhs = typeInference(r.lhs, lhs_t, environment); return CExpr.RECORDACCESS(lhs, r.field); } // default, don't do anything return lhs; } protected Type updateRecordFieldType(Type src, String field, Type type) { if(src instanceof Type.Record) { Type.Record rt = (Type.Record) src; HashMap<String,Type> types = new HashMap<String,Type>(rt.fields()); types.put(field, type); return Type.T_RECORD(types); } else if(src instanceof Type.Union) { Type.Union tu = (Type.Union) src; Type t = Type.T_VOID; for(Type b : tu.bounds()) { t = Type.leastUpperBound(t,updateRecordFieldType(b,field,type)); } return t; } // no can do return type; } */ protected Triple<Entry,Env,Env> propagate(Code.IfGoto code, Entry stmt, Env environment) { CExpr lhs = infer(code.lhs,stmt,environment); CExpr rhs = infer(code.rhs,stmt,environment); Type lhs_t = lhs.type(); Type rhs_t = rhs.type(); Type lub = Type.leastUpperBound(lhs_t,rhs_t); switch(code.op) { case LT: case LTEQ: case GT: case GTEQ: checkIsSubtype(Type.T_REAL, lub, stmt); break; case EQ: case NEQ: if (!Type.isSubtype(lhs_t, rhs_t) && !Type.isSubtype(rhs_t, lhs_t)) { syntaxError("incomparable types: " + lhs_t + " and " + rhs_t, filename, stmt); } break; case ELEMOF: { Type element; if(rhs_t instanceof Type.List){ element = ((Type.List)rhs_t).element(); } else if(rhs_t instanceof Type.Set){ element = ((Type.Set)rhs_t).element(); } else { syntaxError("expected set or list, found: " + rhs_t,filename,stmt); return null; } if (!Type.isSubtype(element, lhs_t)) { syntaxError("incomparable types: " + lhs_t + " and " + rhs_t, filename, stmt); } break; } case SUBSET: case SUBSETEQ: if (!Type.isSubtype(lhs_t, rhs_t) && !Type.isSubtype(rhs_t, lhs_t)) { syntaxError("incomparable types: " + lhs_t + " and " + rhs_t, filename, stmt); } checkIsSubtype(Type.T_SET(Type.T_ANY),lhs_t,stmt); checkIsSubtype(Type.T_SET(Type.T_ANY),rhs_t,stmt); break; case NSUBTYPEEQ: case SUBTYPEEQ: Value.TypeConst tc = (Value.TypeConst) rhs; Code ncode = code; Env trueEnv = null; Env falseEnv = null; if(Type.isSubtype(tc.type,lhs_t)) { // DEFINITE TRUE CASE trueEnv = environment; if (code.op == Code.COP.SUBTYPEEQ) { ncode = new Code.Goto(code.target); } else { ncode = new Code.Skip(); } } else if (Type.greatestLowerBound(lhs_t, tc.type) == Type.T_VOID) { // DEFINITE FALSE CASE falseEnv = environment; if (code.op == Code.COP.NSUBTYPEEQ) { ncode = new Code.Goto(code.target); } else { ncode = new Code.Skip(); } } else { ncode = new Code.IfGoto(code.op, lhs, rhs, code.target); trueEnv = new Env(environment); falseEnv = new Env(environment); typeInference(lhs,tc.type,tc.type,trueEnv, falseEnv); } stmt = new Entry(ncode,stmt.attributes()); if(code.op == Code.COP.SUBTYPEEQ) { return new Triple(stmt,trueEnv,falseEnv); } else { // environments are the other way around! return new Triple(stmt,falseEnv,trueEnv); } } code = new Code.IfGoto(code.op, lhs, rhs, code.target); stmt = new Entry(code,stmt.attributes()); return new Triple<Entry,Env,Env>(stmt,environment,environment); } protected void typeInference(CExpr lhs, Type trueType, Type falseType, HashMap<String, Type> trueEnv, HashMap<String, Type> falseEnv) { // System.out.println(lhs + " => " + trueType + " => " + falseType); // Now, perform the actual type inference if (lhs instanceof CExpr.Variable) { CExpr.Variable v = (CExpr.Variable) lhs; Type glb = Type.greatestLowerBound(v.type, trueType); Type gdiff = Type.leastDifference(v.type, falseType); // System.out.println("\nGLB(1): " + trueType // + " & " + v.type + " = " + glb); // System.out.println("GDIFF(1): " + v.type + " - " // + falseType + " = " + gdiff); trueEnv.put(v.name, glb); falseEnv.put(v.name, gdiff); } else if (lhs instanceof CExpr.Register) { CExpr.Register reg = (CExpr.Register) lhs; String name = "%" + reg.index; Type glb = Type.greatestLowerBound(reg.type,trueType); Type gdiff = Type.leastDifference(reg.type, falseType); // System.out.println("\nGLB(2): " + trueType // + " & " + reg.type + " = " + glb); // System.out.println("GDIFF(2): " + reg.type + " - " // + falseType + " = " + gdiff); trueEnv.put(name, glb); falseEnv.put(name, gdiff); } else if (lhs instanceof RecordAccess) { RecordAccess ta = (RecordAccess) lhs; Type.Record lhs_t = Type.effectiveRecordType(ta.lhs.type()); if (lhs_t != null) { HashMap<String, Type> ttypes = new HashMap<String, Type>(); HashMap<String, Type> ftypes = new HashMap<String, Type>(); for (Map.Entry<String, Type> e : lhs_t.fields().entrySet()) { String key = e.getKey(); ttypes.put(key, e.getValue()); ftypes.put(key, Type.T_VOID); } Type glb = Type.greatestLowerBound(trueType, lhs_t.fields() .get(ta.field)); //System.out.println("\nGLB(3): " + trueType + " & " + lhs_t.types.get(ta.field) + " = " + glb); ttypes.put(ta.field, glb); ftypes.put(ta.field, glb); typeInference(ta.lhs, Type.T_RECORD(ttypes), Type .T_RECORD(ftypes), trueEnv, falseEnv); } } } protected Pair<Entry,List<Env>> propagate(Code.Switch code, Entry stmt, Env environment) { CExpr value = infer(code.value,stmt,environment); ArrayList<Env> envs = new ArrayList<Env>(); // TODO: update this code to support type inference of types. That is, // if we switch on a type value then this will update the type of the // value. for(int i=0;i!=code.branches.size();++i) { envs.add(environment); } Code ncode = new Code.Switch(value,code.defaultTarget,code.branches); return new Pair(new Entry(ncode,stmt.attributes()),envs); } protected Pair<Block, Env> propagate(Code.ForAll start, Block body, Entry stmt, Env environment) { // First, create modifies set and type the invariant HashSet<String> modifies = new HashSet<String>(); Block invariant = start.invariant; for(Entry s : body) { if(s.code instanceof Code.Assign) { Code.Assign a = (Code.Assign) s.code; if(a.lhs != null) { LVar v = CExpr.extractLVar(a.lhs); modifies.add(v.name()); } } } // Now, type the source CExpr src = infer(start.source, stmt, environment); Type src_t = src.type(); Type elem_t; if(src_t instanceof Type.List) { elem_t = ((Type.List)src_t).element(); } else if(src_t instanceof Type.Set){ elem_t = ((Type.Set)src_t).element(); } else { syntaxError("expected set or list, found: " + src_t,filename,stmt); return null; // deadcode } Block blk = new Block(); if (elem_t == Type.T_VOID) { // This indicates a loop over an empty list. This legitimately can // happen as a result of substitution for contraints or pre/post // conditions. return new Pair<Block,Env>(blk,environment); } // create environment specific for loop body Env loopEnv = new Env(environment); String loopVar = "%" + start.variable.index; loopEnv.put(loopVar, elem_t); Pair<Block,Env> r = null; Env old = null; do { // iterate until a fixed point reached old = r != null ? r.second() : loopEnv; r = propagate(body,old); } while(!r.second().equals(old)); environment = join(environment,r.second()); if(invariant != null) { // we have to propagate the invariant here, since we must wait until // the proper environment is known. invariant = propagate(invariant,environment).first(); } // now construct final modifies set HashSet<CExpr.LVar> mods = new HashSet<CExpr.LVar>(); for(String v : modifies) { Type t = environment.get(v); if(t == null) { continue; } if(v.charAt(0) == '%') { mods.add(CExpr.REG(t, Integer.parseInt(v.substring(1)))); } else { mods.add(CExpr.VAR(t, v)); } } // Finally, update the code blk.add(new Code.Forall(start.label, invariant, CExpr.REG(elem_t, start.variable.index), src, mods), stmt.attributes()); blk.addAll(r.first()); blk.add(end); return new Pair<Block,Env>(blk,join(environment,r.second())); } protected Pair<Block, Env> propagate(Code.Loop start, Code.LoopEnd end, Block body, Entry stmt, Env environment) { HashSet<String> modifies = new HashSet<String>(); Block invariant = start.invariant; for(Entry s : body) { if(s.code instanceof Code.Assign) { Code.Assign a = (Code.Assign) s.code; if(a.lhs != null) { LVar v = CExpr.extractLVar(a.lhs); modifies.add(v.name()); } } } Block blk = new Block(); Pair<Block,Env> r = propagate(body,environment); Env old = null; do { // iterate until a fixed point reached old = r != null ? r.second() : environment; r = propagate(body,old); } while(!r.second().equals(old)); environment = join(environment,r.second()); if(invariant != null) { // we have to propagate the invariant here, since we must wait until // the proper environment is known. invariant = propagate(invariant,environment).first(); } // now construct final modifies set HashSet<CExpr.LVar> mods = new HashSet<CExpr.LVar>(); for(String v : modifies) { Type t = environment.get(v); if(t == null) { continue; } if(v.charAt(0) == '%') { mods.add(CExpr.REG(t, Integer.parseInt(v.substring(1)))); } else { mods.add(CExpr.VAR(t, v)); } } blk.add(new Loop(start.label,invariant,mods),stmt.attributes()); blk.addAll(r.first()); blk.add(end); return new Pair<Block,Env>(blk,environment); } /** * Bind function is responsible for determining the true type of a method or * function being invoked. To do this, it must find the function/method * with the most precise type that matches the argument types. * * @param nid * @param receiver * @param paramTypes * @param elem * @return * @throws ResolveError */ protected Type.Fun bindFunction(NameID nid, Type.Process receiver, List<Type> paramTypes, SyntacticElement elem) throws ResolveError { Type.Fun target = Type.T_FUN(receiver, Type.T_ANY,paramTypes); Type.Fun candidate = null; List<Type.Fun> targets = lookupMethod(nid.module(),nid.name()); for (Type.Fun ft : targets) { Type funrec = ft.receiver(); if (receiver == funrec || (receiver != null && funrec != null && Type.isSubtype( funrec, receiver))) { // receivers match up OK ... if (ft.params().size() == paramTypes.size() && paramSubtypes(ft, target) && (candidate == null || paramSubtypes(candidate,ft))) { candidate = ft; } } } // Check whether we actually found something. If not, print a useful // error message. if(candidate == null) { String msg = "no match for " + nid.name() + parameterString(paramTypes); boolean firstTime = true; int count = 0; for(Type.Fun ft : targets) { if(firstTime) { msg += "\n\tfound: " + nid.name() + parameterString(ft.params()); } else { msg += "\n\tand: " + nid.name() + parameterString(ft.params()); } if(++count < targets.size()) { msg += ","; } } syntaxError(msg + "\n",filename,elem); } return candidate; } private boolean paramSubtypes(Type.Fun f1, Type.Fun f2) { List<Type> f1_params = f1.params(); List<Type> f2_params = f2.params(); if(f1_params.size() == f2_params.size()) { for(int i=0;i!=f1_params.size();++i) { if(!Type.isSubtype(f1_params.get(i),f2_params.get(i))) { return false; } } return true; } return false; } private String parameterString(List<Type> paramTypes) { String paramStr = "("; boolean firstTime = true; for(Type t : paramTypes) { if(!firstTime) { paramStr += ","; } firstTime=false; paramStr += t; } return paramStr + ")"; } protected List<Type.Fun> lookupMethod(ModuleID mid, String name) throws ResolveError { Module module = loader.loadModule(mid); ArrayList<Type.Fun> rs = new ArrayList<Type.Fun>(); for (Module.Method m : module.method(name)) { rs.add(m.type()); } return rs; } protected <T extends Type> T checkType(Type t, Class<T> clazz, SyntacticElement elem) { if (clazz.isInstance(t)) { return (T) t; } else { syntaxError("expected type " + clazz.getName() + ", found " + t, filename, elem); return null; } } // Check t1 :> t2 protected void checkIsSubtype(Type t1, Type t2, SyntacticElement elem) { if (!Type.isSubtype(t1, t2)) { syntaxError("expected type " + t1 + ", found " + t2, filename, elem); } } public Env join(Env env1, Env env2) { if (env2 == null) { return env1; } else if (env1 == null) { return env2; } Env env = new Env(); for (int i = 0; i != Math.min(env1.size(), env2.size()); ++i) { env.add(Type.leastUpperBound(env1.get(i), env2.get(i))); } return env; } public static class Env extends ArrayList<Type> { public Env() { } public Env(List<Type> v) { super(v); } public void push(Type t) { add(t); } public Type top() { return get(size()-1); } public Type pop() { return remove(size()-1); } } }
package util; import java.io.File; import java.io.FileOutputStream; import java.util.Collection; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; /** * * @author occidere */ public class ImageCompress { private ImageCompress() {} /** * .zip . * . * @param targetDirectory (.zip .) * @throws Exception */ public static void compress(String targetDirectory) throws Exception { compress(targetDirectory, targetDirectory); } /** * .zip * @param saveFileFullName (.zip .) * @param targetDirectory * @throws Exception */ public static void compress(String saveFileFullName, String targetDirectory) throws Exception { saveFileFullName = removeLastSeparator(saveFileFullName) + ".zip"; targetDirectory = removeLastSeparator(targetDirectory); System.out.printf(" ... "); Collection<File> fileList = FileUtils.listFiles(new File(targetDirectory), null, true); ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(saveFileFullName)); for(File image : fileList) { String canonicalPath = StringUtils.substringAfter(image.getAbsolutePath(), getLastDirectory(targetDirectory)); zipOutputStream.putNextEntry(new ZipEntry(canonicalPath)); zipOutputStream.write(FileUtils.readFileToByteArray(image)); zipOutputStream.closeEntry(); } zipOutputStream.close(); System.out.println(""); } /** * , . * ex) /Users/occidere/Twice -> Twice * @param absolutePathd * @return */ private static String getLastDirectory(String absolutePath) { return StringUtils.substringAfterLast(removeLastSeparator(absolutePath), File.separator); } /** * , (/ \) . * @param path * @return */ private static String removeLastSeparator(String path) { String separator = File.separator; return StringUtils.containsOnly(path, separator) ? path : StringUtils.stripEnd(path, separator); } }
package org.owasp.esapi.reference; import java.io.ByteArrayInputStream; import java.text.DateFormat; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.owasp.esapi.ESAPI; import org.owasp.esapi.Validator; import org.owasp.esapi.errors.IntrusionException; import org.owasp.esapi.errors.ValidationException; import org.owasp.esapi.http.TestHttpServletRequest; import org.owasp.esapi.http.TestHttpServletResponse; /** * The Class ValidatorTest. * * @author Jeff Williams (jeff.williams@aspectsecurity.com) */ public class ValidatorTest extends TestCase { /** * Instantiates a new validator test. * * @param testName * the test name */ public ValidatorTest(String testName) { super(testName); } /** * {@inheritDoc} */ protected void setUp() throws Exception { // none } /** * {@inheritDoc} */ protected void tearDown() throws Exception { // none } /** * Suite. * * @return the test */ public static Test suite() { TestSuite suite = new TestSuite(ValidatorTest.class); return suite; } /** * Test of isValidCreditCard method, of class org.owasp.esapi.Validator. */ public void testIsValidCreditCard() { System.out.println("isValidCreditCard"); Validator instance = ESAPI.validator(); assertTrue(instance.isValidCreditCard("test", "1234 9876 0000 0008", false)); assertTrue(instance.isValidCreditCard("test", "1234987600000008", false)); assertFalse(instance.isValidCreditCard("test", "12349876000000081", false)); assertFalse(instance.isValidCreditCard("test", "4417 1234 5678 9112", false)); } /** * Test of isValidEmailAddress method, of class org.owasp.esapi.Validator. */ public void testisValidInput() { System.out.println("isValidInput"); Validator instance = ESAPI.validator(); assertTrue(instance.isValidInput("test", "jeff.williams@aspectsecurity.com", "Email", 100, false)); assertFalse(instance.isValidInput("test", "jeff.williams@@aspectsecurity.com", "Email", 100, false)); assertFalse(instance.isValidInput("test", "jeff.williams@aspectsecurity", "Email", 100, false)); assertTrue(instance.isValidInput("test", "123.168.100.234", "IPAddress", 100, false)); assertTrue(instance.isValidInput("test", "192.168.1.234", "IPAddress", 100, false)); assertFalse(instance.isValidInput("test", "..168.1.234", "IPAddress", 100, false)); assertFalse(instance.isValidInput("test", "10.x.1.234", "IPAddress", 100, false)); assertTrue(instance.isValidInput("test", "http: assertFalse(instance.isValidInput("test", "http: assertFalse(instance.isValidInput("test", "http: assertTrue(instance.isValidInput("test", "078-05-1120", "SSN", 100, false)); assertTrue(instance.isValidInput("test", "078 05 1120", "SSN", 100, false)); assertTrue(instance.isValidInput("test", "078051120", "SSN", 100, false)); assertFalse(instance.isValidInput("test", "987-65-4320", "SSN", 100, false)); assertFalse(instance.isValidInput("test", "000-00-0000", "SSN", 100, false)); assertFalse(instance.isValidInput("test", "(555) 555-5555", "SSN", 100, false)); assertFalse(instance.isValidInput("test", "test", "SSN", 100, false)); assertTrue(instance.isValidInput("test", null, "Email", 100, true)); assertFalse(instance.isValidInput("test", null, "Email", 100, false)); } /** * Test of isValidSafeHTML method, of class org.owasp.esapi.Validator. */ public void testIsValidSafeHTML() { System.out.println("isValidSafeHTML"); Validator instance = ESAPI.validator(); assertTrue(instance.isValidSafeHTML("test", "<b>Jeff</b>", 100, false)); assertTrue(instance.isValidSafeHTML("test", "<a href=\"http: assertFalse(instance.isValidSafeHTML("test", "Test. <script>alert(document.cookie)</script>", 100, false)); // TODO: waiting for a way to validate text headed for an attribute for scripts // This would be nice to catch, but just looks like text to AntiSamy // assertFalse(instance.isValidSafeHTML("test", "\" onload=\"alert(document.cookie)\" ")); } /** * Test of getValidSafeHTML method, of class org.owasp.esapi.Validator. */ public void testGetValidSafeHTML() throws Exception{ System.out.println("getValidSafeHTML"); Validator instance = ESAPI.validator(); String test1 = "<b>Jeff</b>"; String result1 = instance.getValidSafeHTML("test", test1, 100, false); assertEquals(test1, result1); String test2 = "<a href=\"http: String result2 = instance.getValidSafeHTML("test", test2, 100, false); assertEquals(test2, result2); String test3 = "Test. <script>alert(document.cookie)</script>"; String result3 = instance.getValidSafeHTML("test", test3, 100, false); assertEquals("Test.", result3); // TODO: ENHANCE waiting for a way to validate text headed for an attribute for scripts // This would be nice to catch, but just looks like text to AntiSamy // assertFalse(instance.isValidSafeHTML("test", "\" onload=\"alert(document.cookie)\" ")); // String result4 = instance.getValidSafeHTML("test", test4); // assertEquals("", result4); } /** * Test of isValidListItem method, of class org.owasp.esapi.Validator. */ public void testIsValidListItem() { System.out.println("isValidListItem"); Validator instance = ESAPI.validator(); List list = new ArrayList(); list.add("one"); list.add("two"); assertTrue(instance.isValidListItem("test", "one", list)); assertFalse(instance.isValidListItem("test", "three", list)); } /** * Test of isValidNumber method, of class org.owasp.esapi.Validator. */ public void testIsValidNumber() { System.out.println("isValidNumber"); Validator instance = ESAPI.validator(); //testing negative range assertFalse(instance.isValidNumber("test", "-4", 1, 10, false)); assertTrue(instance.isValidNumber("test", "-4", -10, 10, false)); //testing null value assertTrue(instance.isValidNumber("test", null, -10, 10, true)); assertFalse(instance.isValidNumber("test", null, -10, 10, false)); //testing empty string assertTrue(instance.isValidNumber("test", "", -10, 10, true)); assertFalse(instance.isValidNumber("test", "", -10, 10, false)); //testing improper range assertFalse(instance.isValidNumber("test", "5", 10, -10, false)); //testing non-integers assertTrue(instance.isValidNumber("test", "4.3214", -10, 10, true)); assertTrue(instance.isValidNumber("test", "-1.65", -10, 10, true)); //other testing assertTrue(instance.isValidNumber("test", "4", 1, 10, false)); assertTrue(instance.isValidNumber("test", "400", 1, 10000, false)); assertTrue(instance.isValidNumber("test", "400000000", 1, 400000000, false)); assertFalse(instance.isValidNumber("test", "4000000000000", 1, 10000, false)); assertFalse(instance.isValidNumber("test", "alsdkf", 10, 10000, false)); assertFalse(instance.isValidNumber("test", "--10", 10, 10000, false)); assertFalse(instance.isValidNumber("test", "14.1414234x", 10, 10000, false)); assertFalse(instance.isValidNumber("test", "Infinity", 10, 10000, false)); assertFalse(instance.isValidNumber("test", "-Infinity", 10, 10000, false)); assertFalse(instance.isValidNumber("test", "NaN", 10, 10000, false)); assertFalse(instance.isValidNumber("test", "-NaN", 10, 10000, false)); assertFalse(instance.isValidNumber("test", "+NaN", 10, 10000, false)); assertTrue(instance.isValidNumber("test", "1e-6", -999999999, 999999999, false)); assertTrue(instance.isValidNumber("test", "-1e-6", -999999999, 999999999, false)); } public void testIsValidInteger() { System.out.println("isValidInteger"); Validator instance = ESAPI.validator(); //testing negative range assertFalse(instance.isValidInteger("test", "-4", 1, 10, false)); assertTrue(instance.isValidInteger("test", "-4", -10, 10, false)); //testing null value assertTrue(instance.isValidInteger("test", null, -10, 10, true)); assertFalse(instance.isValidInteger("test", null, -10, 10, false)); //testing empty string assertTrue(instance.isValidInteger("test", "", -10, 10, true)); assertFalse(instance.isValidInteger("test", "", -10, 10, false)); //testing improper range assertFalse(instance.isValidInteger("test", "5", 10, -10, false)); //testing non-integers assertFalse(instance.isValidInteger("test", "4.3214", -10, 10, true)); assertFalse(instance.isValidInteger("test", "-1.65", -10, 10, true)); //other testing assertTrue(instance.isValidInteger("test", "4", 1, 10, false)); assertTrue(instance.isValidInteger("test", "400", 1, 10000, false)); assertTrue(instance.isValidInteger("test", "400000000", 1, 400000000, false)); assertFalse(instance.isValidInteger("test", "4000000000000", 1, 10000, false)); assertFalse(instance.isValidInteger("test", "alsdkf", 10, 10000, false)); assertFalse(instance.isValidInteger("test", "--10", 10, 10000, false)); assertFalse(instance.isValidInteger("test", "14.1414234x", 10, 10000, false)); assertFalse(instance.isValidInteger("test", "Infinity", 10, 10000, false)); assertFalse(instance.isValidInteger("test", "-Infinity", 10, 10000, false)); assertFalse(instance.isValidInteger("test", "NaN", 10, 10000, false)); assertFalse(instance.isValidInteger("test", "-NaN", 10, 10000, false)); assertFalse(instance.isValidInteger("test", "+NaN", 10, 10000, false)); assertFalse(instance.isValidInteger("test", "1e-6", -999999999, 999999999, false)); assertFalse(instance.isValidInteger("test", "-1e-6", -999999999, 999999999, false)); } /** * Test of getValidDate method, of class org.owasp.esapi.Validator. */ public void testGetValidDate() throws Exception { System.out.println("getValidDate"); Validator instance = ESAPI.validator(); assertTrue(instance.getValidDate("test", "June 23, 1967", DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US), false ) != null); try { instance.getValidDate("test", "freakshow", DateFormat.getDateInstance(), false ); } catch( ValidationException e ) { // expected } // This test case fails due to an apparent bug in SimpleDateFormat try { instance.getValidDate( "test", "June 32, 2008", DateFormat.getDateInstance(), false ); // fail(); } catch( ValidationException e ) { // expected } } /** * Test of isValidFileName method, of class org.owasp.esapi.Validator. */ public void testIsValidFileName() { System.out.println("isValidFileName"); Validator instance = ESAPI.validator(); assertTrue(instance.isValidFileName("test", "aspect.jar", false)); assertFalse(instance.isValidFileName("test", "", false)); try { instance.isValidFileName("test", "abc/def", false); } catch( IntrusionException e ) { // expected } } /** * Test of isValidDirectoryPath method, of class org.owasp.esapi.Validator. */ public void testIsValidDirectoryPath() { System.out.println("isValidDirectoryPath"); boolean isWindows = (System.getProperty("os.name").indexOf("Windows") != -1 ) ? true : false; Validator instance = ESAPI.validator(); if ( isWindows ) { // Windows paths that don't exist and thus should fail assertFalse(instance.isValidDirectoryPath("test", "c:\\pathNotExist", false)); assertTrue(instance.isValidDirectoryPath("test", "c:\\jeff", false)); assertFalse(instance.isValidDirectoryPath("test", "c:\\temp\\..\\etc", false)); // Windows paths that should pass assertTrue(instance.isValidDirectoryPath("test", "c:\\", false)); // Windows root directory assertTrue(instance.isValidDirectoryPath("test", "c:\\windows", false)); // Windows always exist directory assertTrue(instance.isValidDirectoryPath("test", "c:\\windows\\system32\\cmd.exe", false)); // Windows command shell // Unix specific paths should not pass assertFalse(instance.isValidDirectoryPath("test", "/", false)); // Unix Root directory assertFalse(instance.isValidDirectoryPath("test", "/tmp", false)); // Unix Temporary directory assertFalse(instance.isValidDirectoryPath("test", "/bin/sh", false)); // Unix Standard shell assertTrue(instance.isValidDirectoryPath("test", "/etc/config", false)); // Unix specific paths that should not exist or work assertFalse(instance.isValidDirectoryPath("test", "/etc/pathDoesNotExist", false)); assertFalse(instance.isValidDirectoryPath("test", "/tmp/../etc", false)); } else { // Windows paths should fail assertFalse(instance.isValidDirectoryPath("test", "c:\\pathNotExist", false)); assertFalse(instance.isValidDirectoryPath("test", "c:\\temp\\..\\etc", false)); // Standard Windows locations should fail assertFalse(instance.isValidDirectoryPath("test", "c:\\", false)); // Windows root directory assertFalse(instance.isValidDirectoryPath("test", "c:\\Windows\\temp", false)); // Windows temporary directory assertFalse(instance.isValidDirectoryPath("test", "c:\\Windows\\System32\\cmd.exe", false)); // Windows command shell // Unix specific paths should pass assertTrue(instance.isValidDirectoryPath("test", "/", false)); // Root directory assertTrue(instance.isValidDirectoryPath("test", "/bin", false)); // Always exist directory assertTrue(instance.isValidDirectoryPath("test", "/bin/sh", false)); // Standard shell // Unix specific paths that should not exist or work assertFalse(instance.isValidDirectoryPath("test", "/etc/pathDoesNotExist", false)); assertFalse(instance.isValidDirectoryPath("test", "/tmp/../etc", false)); } } public void testIsValidPrintable() { System.out.println("isValidPrintable"); Validator instance = ESAPI.validator(); assertTrue(instance.isValidPrintable("name", "abcDEF", 100, false)); assertTrue(instance.isValidPrintable("name", "!@#R()*$;><()", 100, false)); byte[] bytes = { 0x60, (byte) 0xFF, 0x10, 0x25 }; assertFalse( instance.isValidPrintable("name", bytes, 100, false ) ); assertFalse(instance.isValidPrintable("name", "%08", 100, false)); } /** * Test of isValidFileContent method, of class org.owasp.esapi.Validator. */ public void testIsValidFileContent() { System.out.println("isValidFileContent"); byte[] content = "This is some file content".getBytes(); Validator instance = ESAPI.validator(); assertTrue(instance.isValidFileContent("test", content, 100, false)); } /** * Test of isValidFileUpload method, of class org.owasp.esapi.Validator. */ public void testIsValidFileUpload() { System.out.println("isValidFileUpload"); String filepath = "/bin"; String filename = "aspect.jar"; byte[] content = "Thisi is some file content".getBytes(); Validator instance = ESAPI.validator(); assertTrue(instance.isValidFileUpload("test", filepath, filename, content, 100, false)); // This will fail on MacOS X, as /etc is actually /private/etc // TODO: Fix canonicalization of symlinks on MacOS X filepath = "/etc"; filename = "aspect.jar"; content = "Thisi is some file content".getBytes(); assertTrue(instance.isValidFileUpload("test", filepath, filename, content, 100, false)); } /** * Test of isValidParameterSet method, of class org.owasp.esapi.Validator. */ public void testIsValidParameterSet() { System.out.println("isValidParameterSet"); Set requiredNames = new HashSet(); requiredNames.add("p1"); requiredNames.add("p2"); requiredNames.add("p3"); Set optionalNames = new HashSet(); optionalNames.add("p4"); optionalNames.add("p5"); optionalNames.add("p6"); TestHttpServletRequest request = new TestHttpServletRequest(); TestHttpServletResponse response = new TestHttpServletResponse(); request.addParameter("p1","value"); request.addParameter("p2","value"); request.addParameter("p3","value"); ESAPI.httpUtilities().setCurrentHTTP(request, response); Validator instance = ESAPI.validator(); assertTrue(instance.isValidHTTPRequestParameterSet("HTTPParameters", requiredNames, optionalNames)); request.addParameter("p4","value"); request.addParameter("p5","value"); request.addParameter("p6","value"); assertTrue(instance.isValidHTTPRequestParameterSet("HTTPParameters", requiredNames, optionalNames)); request.removeParameter("p1"); assertFalse(instance.isValidHTTPRequestParameterSet("HTTPParameters", requiredNames, optionalNames)); } /** * Test safe read line. */ public void testSafeReadLine() { System.out.println("safeReadLine"); ByteArrayInputStream s = new ByteArrayInputStream("testString".getBytes()); Validator instance = ESAPI.validator(); try { instance.safeReadLine(s, -1); fail(); } catch (ValidationException e) { // Expected } s.reset(); try { instance.safeReadLine(s, 4); fail(); } catch (ValidationException e) { // Expected } s.reset(); try { String u = instance.safeReadLine(s, 20); assertEquals("testString", u); } catch (ValidationException e) { fail(); } } }
package xtandem; import interfaces.Ion; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; /** * This class holds the peptide informatin in a map. * @author Thilo Muth * */ public class PeptideMap implements Serializable{ /** * This variable holds the second dimension hash map for the peptide object as value. */ private HashMap<String, Peptide> iPeptideMap = null; /** * This variable holds the first dimension hash map for the peptide hash map as value. */ private HashMap<String, HashMap> iSpectrumAndPeptideMap = null; public PeptideMap(HashMap aRawPeptideMap, ProteinMap aProteinMap, int aNumberOfSpectra){ buildPeptideMap(aRawPeptideMap, aProteinMap, aNumberOfSpectra); } /** * Constructs the 2-dim hashmap, the first dimension is the map with the spectrum-number as key and another hash map as value. * The second dimension has the peptideID (e.g. s171_p2 for spectrum number 171 and the second peptide) and the peptide object as value. * @param aRawPeptideMap * @param aProteinMap * @param aNumberOfSpectra * @return spectrumAndPeptideMap */ private HashMap buildPeptideMap(HashMap aRawPeptideMap, ProteinMap aProteinMap, int aNumberOfSpectra) { // First dimension of the map, which contains the spectra as key and the peptide hash maps as values iSpectrumAndPeptideMap = new HashMap(aNumberOfSpectra); // Hashmap for the peptide objects iPeptideMap = new HashMap<String, Peptide>(); if (aRawPeptideMap != null) { for (int i = 1; i <= aNumberOfSpectra; i++) { // The counter for the peptides int counter = 1; // Check if there are any values given out of the map while (aRawPeptideMap.get("s" + i + "_p" + counter) != null) { // The peptide id is consists of s + spectrum# + _p + peptide# String peptideID = ("s" + i + "_p" + counter).toString(); int peptideStart = Integer.parseInt(aRawPeptideMap.get("start" + "_s" + i +"_p" + counter).toString()); int peptideEnd = Integer.parseInt(aRawPeptideMap.get("end" + "_s" + i +"_p" + counter).toString()); String sequence = aRawPeptideMap.get("seq" + "_s" + i +"_p" + counter).toString().trim(); // Create an instance of a protein. Peptide peptide = new Peptide(peptideID, peptideStart, peptideEnd, sequence); // Set the domain values peptide.setSpectrumNumber(i); peptide.setDomainID(aRawPeptideMap.get("domainid" + "_s" + i +"_p" + counter).toString()); peptide.setDomainStart(Integer.parseInt(aRawPeptideMap.get("domainstart" + "_s" + i +"_p" + counter).toString())); peptide.setDomainEnd(Integer.parseInt(aRawPeptideMap.get("domainend" + "_s" + i +"_p" + counter).toString())); peptide.setDomainExpect(Double.parseDouble(aRawPeptideMap.get("expect" + "_s" + i +"_p" + counter).toString())); peptide.setDomainMh(Double.parseDouble(aRawPeptideMap.get("mh" + "_s" + i +"_p" + counter).toString())); peptide.setDomainDeltaMh(Double.parseDouble(aRawPeptideMap.get("delta" + "_s" + i +"_p" + counter).toString())); peptide.setDomainHyperScore(Double.parseDouble(aRawPeptideMap.get("hyperscore" + "_s" + i +"_p" + counter).toString())); peptide.setDomainNextScore(Double.parseDouble(aRawPeptideMap.get("nextscore" + "_s" + i +"_p" + counter).toString())); ArrayList<Ion> ionList = new ArrayList<Ion>(); // if(aRawPeptideMap.get("a_score" + "_s" + i +"_p" + counter) != null ){ // double aScore = Double.parseDouble(aRawPeptideMap.get("a_score" + "_s" + i +"_p" + counter).toString()); // int aNumber = Integer.parseInt(aRawPeptideMap.get("a_ions" + "_s" + i +"_p" + counter).toString()); // Ion aIon = new Ion (aNumber, aScore); // aIon.setType(interfaces.aION_TYPE); // ionList.add(aIon); // if (aRawPeptideMap.get("b_score" + "_s" + i +"_p" + counter) != null){ // double bScore = Double.parseDouble(aRawPeptideMap.get("b_score" + "_s" + i +"_p" + counter).toString()); // int bNumber = Integer.parseInt(aRawPeptideMap.get("b_ions" + "_s" + i +"_p" + counter).toString()); // Ion bIon = new Ion (bNumber, bScore); // bIon.setType(interfaces.bION_TYPE); // ionList.add(bIon); // if(aRawPeptideMap.get("c_score" + "_s" + i +"_p" + counter) != null){ // double cScore = Double.parseDouble(aRawPeptideMap.get("c_score" + "_s" + i +"_p" + counter).toString()); // int cNumber = Integer.parseInt(aRawPeptideMap.get("c_ions" + "_s" + i +"_p" + counter).toString()); // Ion cIon = new Ion (cNumber, cScore); // cIon.setType(interfaces.cION_TYPE); // ionList.add(cIon); // if(aRawPeptideMap.get("x_score" + "_s" + i +"_p" + counter) != null){ // double xScore = Double.parseDouble(aRawPeptideMap.get("x_score" + "_s" + i +"_p" + counter).toString()); // int xNumber = Integer.parseInt(aRawPeptideMap.get("x_ions" + "_s" + i +"_p" + counter).toString()); // Ion xIon = new Ion (xNumber, xScore); // xIon.setType(interfaces.xION_TYPE); // ionList.add(xIon); // if(aRawPeptideMap.get("y_score" + "_s" + i +"_p" + counter) != null){ // double yScore = Double.parseDouble(aRawPeptideMap.get("y_score" + "_s" + i +"_p" + counter).toString()); // int yNumber = Integer.parseInt(aRawPeptideMap.get("y_ions" + "_s" + i +"_p" + counter).toString()); // Ion yIon = new Ion (yNumber, yScore); // yIon.setType(interfaces.yION_TYPE); // ionList.add(yIon); // if(aRawPeptideMap.get("z_score" + "_s" + i +"_p" + counter) != null){ // double zScore = Double.parseDouble(aRawPeptideMap.get("z_score" + "_s" + i +"_p" + counter).toString()); // int zNumber = Integer.parseInt(aRawPeptideMap.get("z_ions" + "_s" + i +"_p" + counter).toString()); // Ion zIon = new Ion (zNumber, zScore); // zIon.setType(interfaces.zION_TYPE); // ionList.add(zIon); peptide.setIons(ionList); peptide.setUpFlankSequence(aRawPeptideMap.get("pre" + "_s" + i +"_p" + counter).toString()); peptide.setDownFlankSequence(aRawPeptideMap.get("post" + "_s" + i +"_p" + counter).toString()); peptide.setDomainSequence(aRawPeptideMap.get("domainseq" + "_s" + i +"_p" + counter).toString()); peptide.setMissedCleavages(Integer.parseInt(aRawPeptideMap.get("missed_cleavages" + "_s" + i +"_p" + counter).toString())); // Put the peptide into the map, value is the id. iPeptideMap.put(peptideID, peptide); // Update the PeptideHit in the ProteinMap. // PeptideHit lPeptideHit = (PeptideHit) lSecondDimension.get(lCount - 1); // int lNumberOfProteinHits = lPeptideHit.getProteinHits().size(); // for (int k = 0; k < lNumberOfProteinHits; k++) { // ProteinHit lProteinHit = (ProteinHit) lPeptideHit.getProteinHits().get(k); // aProteinMap.addProteinSource(lProteinHit.getAccession(), i, lCount); counter++; } iSpectrumAndPeptideMap.put("s" + i, iPeptideMap); } } return iSpectrumAndPeptideMap; } /** * Returns the 2-dim spectrum and peptide map. * @return iSpectrumAndPeptideMap HashMap */ public HashMap<String, HashMap> getSpectrumAndPeptideMap() { return iSpectrumAndPeptideMap; } /** * Retrieve all possible peptide objects for a given spectrum. * @param aSpectrumNumber * @return peptideList ArrayList */ public ArrayList<Peptide> getAllPeptides(int aSpectrumNumber){ ArrayList<Peptide> peptideList = new ArrayList<Peptide>(); HashMap<String, Peptide> peptideMap = iSpectrumAndPeptideMap.get("s" + aSpectrumNumber); int pepCount = 1; while (peptideMap.get("s" + aSpectrumNumber + "_p" + pepCount) != null) { peptideList.add((Peptide) peptideMap.get("s" + aSpectrumNumber + "_p" + pepCount)); pepCount++; } return peptideList; } /** * Returns a specific peptide by an index. * @param aSpectrumNumber * @param index * @return peptide Peptide */ public Peptide getPeptideByIndex(int aSpectrumNumber, int index){ ArrayList<Peptide> peptideList = this.getAllPeptides(aSpectrumNumber); Peptide peptide = null; if(peptideList.get(index-1) != null){ peptide = (Peptide) peptideList.get(index-1); } return peptide; } /** * Returns the number of peptides for a given spectrum * @param aSpectrumNumber * @return */ public int getNumberOfPeptides(int aSpectrumNumber){ return this.getAllPeptides(aSpectrumNumber).size(); } }
package com.ecyrd.jspwiki; import junit.framework.*; import java.io.*; import java.util.*; public class TranslatorReaderTest extends TestCase { Properties props = new Properties(); public TranslatorReaderTest( String s ) { super( s ); } public void setUp() throws Exception { props.load( getClass().getClassLoader().getResourceAsStream("/jspwiki.properties") ); } public void tearDown() { } private String translate( String src ) throws IOException, NoRequiredPropertyException { WikiContext context = new WikiContext( new TestEngine(props), "testpage" ); Reader r = new TranslatorReader( context, new BufferedReader( new StringReader(src)) ); StringWriter out = new StringWriter(); int c; while( ( c=r.read()) != -1 ) { out.write( c ); } return out.toString(); } public void testHyperlinks2() throws Exception { String src = "This should be a [hyperlink]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=Hyperlink\">hyperlink</A>\n", translate(src) ); } public void testHyperlinks3() throws Exception { String src = "This should be a [hyperlink too]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperlinkToo\">hyperlink too</A>\n", translate(src) ); } public void testHyperlinks4() throws Exception { String src = "This should be a [HyperLink]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>\n", translate(src) ); } public void testHyperlinks5() throws Exception { String src = "This should be a [here|HyperLink]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">here</A>\n", translate(src) ); } public void testHyperlinksExt() throws Exception { String src = "This should be a [http: assertEquals( "This should be a <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testHyperlinksExt2() throws Exception { String src = "This should be a [link|http: assertEquals( "This should be a <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testHyperlinkJS1() throws Exception { String src = "This should be a [link|http: assertEquals( "This should be a <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testHyperlinksInterWiki1() throws Exception { String src = "This should be a [link|JSPWiki:HyperLink]"; assertEquals( "This should be a <A CLASS=\"interwiki\" HREF=\"http: translate(src) ); } public void testExtraPagename1() throws Exception { String src = "Link [test_page]"; assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=Test_page\">test_page</A>\n", translate(src) ); } public void testExtraPagename2() throws Exception { String src = "Link [test.page]"; assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=Test.page\">test.page</A>\n", translate(src) ); } public void testExtraPagename3() throws Exception { String src = "Link [.testpage_]"; assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=.testpage_\">.testpage_</A>\n", translate(src) ); } public void testInlineImages() throws Exception { String src = "Link [test|http: assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http: translate(src) ); } public void testInlineImages2() throws Exception { String src = "Link [test|http: assertEquals("Link <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testInlineImages3() throws Exception { String src = "Link [test|http://images.com/testi]"; assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http://images.com/testi\" ALT=\"test\">\n", translate(src) ); } public void testInlineImages4() throws Exception { String src = "Link [test|http://foobar.jpg]"; assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http://foobar.jpg\" ALT=\"test\">\n", translate(src) ); } public void testScandicPagename1() throws Exception { String src = "Link [Test]"; assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=%C5%E4Test\">Test</A>\n", translate(src)); } public void testParagraph() throws Exception { String src = "1\n\n2\n\n3"; assertEquals( "1\n<P>\n2\n<P>\n3\n", translate(src) ); } public void testLinebreak() throws Exception { String src = "1\\\\2"; assertEquals( "1<BR>2\n", translate(src) ); } public void testTT() throws Exception { String src = "1{{2345}}6"; assertEquals( "1<TT>2345</TT>6\n", translate(src) ); } public void testPre() throws Exception { String src = "1{{{2345}}}6"; assertEquals( "1<PRE>2345</PRE>6\n", translate(src) ); } public void testPre2() throws Exception { String src = "1 {{{ {{{ 2345 }}} }}} 6"; assertEquals( "1 <PRE> {{{ 2345 </PRE> }}} 6\n", translate(src) ); } public void testList1() throws Exception { String src = "A list:\n* One\n* Two\n* Three\n"; assertEquals( "A list:\n<UL>\n<LI> One\n<LI> Two\n<LI> Three\n</UL>\n", translate(src) ); } /** Plain multi line testing: <pre> * One continuing * Two * Three </pre> */ public void testMultilineList1() throws Exception { String src = "A list:\n* One\n continuing.\n* Two\n* Three\n"; assertEquals( "A list:\n<UL>\n<LI> One\n continuing.\n<LI> Two\n<LI> Three\n</UL>\n", translate(src) ); } public void testMultilineList2() throws Exception { String src = "A list:\n* One\n continuing.\n* Two\n* Three\nShould be normal."; assertEquals( "A list:\n<UL>\n<LI> One\n continuing.\n<LI> Two\n<LI> Three\n</UL>\nShould be normal.\n", translate(src) ); } public void testHTML() throws Exception { String src = "<B>Test</B>"; assertEquals( "&lt;B&gt;Test&lt;/B&gt;\n", translate(src) ); } public void testHTML2() throws Exception { String src = "<P>"; assertEquals( "&lt;P&gt;\n", translate(src) ); } public void testQuotes() throws Exception { String src = "\"Test\"\""; assertEquals( "&quot;Test&quot;&quot;\n", translate(src) ); } public void testItalicAcrossLinebreak() throws Exception { String src="''This is a\ntest.''"; assertEquals( "<I>This is a\ntest.</I>\n", translate(src) ); } public void testBoldAcrossLinebreak() throws Exception { String src="__This is a\ntest.__"; assertEquals( "<B>This is a\ntest.</B>\n", translate(src) ); } public void testBoldItalic() throws Exception { String src="__This ''is'' a test.__"; assertEquals( "<B>This <I>is</I> a test.</B>\n", translate(src) ); } public void testFootnote1() throws Exception { String src="Footnote[1]"; assertEquals( "Footnote<A CLASS=\"footnoteref\" HREF=\"#ref1\">[1]</A>\n", translate(src) ); } public void testFootnote2() throws Exception { String src="[#2356] Footnote."; assertEquals( "<A CLASS=\"footnote\" NAME=\"ref2356\">[#2356]</A> Footnote.\n", translate(src) ); } /** Check an reported error condition where empty list items could cause crashes */ public void testEmptySecondLevelList() throws Exception { String src="A\n\n**\n\nB"; assertEquals( "A\n<P>\n<UL>\n<UL>\n<LI>\n</UL>\n</UL>\n<P>\nB\n", translate(src) ); } public void testEmptySecondLevelList2() throws Exception { String src="A\n\n##\n\nB"; assertEquals( "A\n<P>\n<OL>\n<OL>\n<LI>\n</OL>\n</OL>\n<P>\nB\n", translate(src) ); } public void testPluginInsert() throws Exception { String src="[{INSERT com.ecyrd.jspwiki.plugin.SamplePlugin WHERE text=test}]"; assertEquals( "test\n", translate(src) ); } public void testTable1() throws Exception { String src="|| heading || heading2 \n| Cell 1 | Cell 2 \n| Cell 3 | Cell 4\n\n"; assertEquals( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n"+ "<THEAD>\n"+ "<TR><TD> heading <TD> heading2 </TR>\n"+ "</THEAD>\n"+ "<TBODY>\n"+ "<TR><TD> Cell 1 <TD> Cell 2 </TR>\n"+ "<TR><TD> Cell 3 <TD> Cell 4</TR>\n"+ "</TBODY>\n"+ "</TABLE><P>\n", translate(src) ); } public static Test suite() { return new TestSuite( TranslatorReaderTest.class ); } }
package com.ecyrd.jspwiki; import junit.framework.*; import java.io.*; import java.util.*; public class TranslatorReaderTest extends TestCase { Properties props = new Properties(); public TranslatorReaderTest( String s ) { super( s ); } public void setUp() throws Exception { props.load( getClass().getClassLoader().getResourceAsStream("/jspwiki.properties") ); } public void tearDown() { } private String translate( String src ) throws IOException { Reader r = new TranslatorReader( new TestEngine( props ), new BufferedReader( new StringReader(src)) ); StringWriter out = new StringWriter(); int c; while( ( c=r.read()) != -1 ) { out.write( c ); } return out.toString(); } public void testHyperlinks2() throws Exception { String src = "This should be a [hyperlink]"; assertEquals( "This should be a <A HREF=\"Wiki.jsp?page=Hyperlink\">hyperlink</A>\n", translate(src) ); } public void testHyperlinks3() throws Exception { String src = "This should be a [hyperlink too]"; assertEquals( "This should be a <A HREF=\"Wiki.jsp?page=HyperlinkToo\">hyperlink too</A>\n", translate(src) ); } public void testHyperlinks4() throws Exception { String src = "This should be a [HyperLink]"; assertEquals( "This should be a <A HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>\n", translate(src) ); } public void testHyperlinks5() throws Exception { String src = "This should be a [here|HyperLink]"; assertEquals( "This should be a <A HREF=\"Wiki.jsp?page=HyperLink\">here</A>\n", translate(src) ); } public void testHyperlinksExt() throws Exception { String src = "This should be a [http: assertEquals( "This should be a <A HREF=\"http: translate(src) ); } public void testHyperlinksExt2() throws Exception { String src = "This should be a [link|http: assertEquals( "This should be a <A HREF=\"http: translate(src) ); } public void testParagraph() throws Exception { String src = "1\n\n2\n\n3"; assertEquals( "1\n<P>\n2\n<P>\n3\n", translate(src) ); } public void testLinebreak() throws Exception { String src = "1\\\\2"; assertEquals( "1<BR>2\n", translate(src) ); } public void testTT() throws Exception { String src = "1{{2345}}6"; assertEquals( "1<TT>2345</TT>6\n", translate(src) ); } public void testPre() throws Exception { String src = "1{{{2345}}}6"; assertEquals( "1<PRE>2345</PRE>6\n", translate(src) ); } public void testList1() throws Exception { String src = "A list:\n* One\n* Two\n* Three\n"; assertEquals( "A list:\n<UL>\n<LI> One\n<LI> Two\n<LI> Three\n</UL>\n", translate(src) ); } public void testHTML() throws Exception { String src = "<B>Test</B>"; assertEquals( "&lt;B&gt;Test&lt;/B&gt;\n", translate(src) ); } public void testHTML2() throws Exception { String src = "<P>"; assertEquals( "&lt;P&gt;\n", translate(src) ); } public static Test suite() { return new TestSuite( TranslatorReaderTest.class ); } }
package com.ecyrd.jspwiki; import junit.framework.*; import java.io.*; import java.util.*; public class TranslatorReaderTest extends TestCase { Properties props = new Properties(); public TranslatorReaderTest( String s ) { super( s ); } public void setUp() throws Exception { props.load( getClass().getClassLoader().getResourceAsStream("/jspwiki.properties") ); } public void tearDown() { } private String translate( String src ) throws IOException, NoRequiredPropertyException { WikiContext context = new WikiContext( new TestEngine(props), "testpage" ); Reader r = new TranslatorReader( context, new BufferedReader( new StringReader(src)) ); StringWriter out = new StringWriter(); int c; while( ( c=r.read()) != -1 ) { out.write( c ); } return out.toString(); } public void testHyperlinks2() throws Exception { String src = "This should be a [hyperlink]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=Hyperlink\">hyperlink</A>\n", translate(src) ); } public void testHyperlinks3() throws Exception { String src = "This should be a [hyperlink too]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperlinkToo\">hyperlink too</A>\n", translate(src) ); } public void testHyperlinks4() throws Exception { String src = "This should be a [HyperLink]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>\n", translate(src) ); } public void testHyperlinks5() throws Exception { String src = "This should be a [here|HyperLink]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">here</A>\n", translate(src) ); } public void testHyperlinksExt() throws Exception { String src = "This should be a [http: assertEquals( "This should be a <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testHyperlinksExt2() throws Exception { String src = "This should be a [link|http: assertEquals( "This should be a <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testHyperlinkJS1() throws Exception { String src = "This should be a [link|http: assertEquals( "This should be a <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testHyperlinksInterWiki1() throws Exception { String src = "This should be a [link|JSPWiki:HyperLink]"; assertEquals( "This should be a <A CLASS=\"interwiki\" HREF=\"http: translate(src) ); } public void testExtraPagename1() throws Exception { String src = "Link [test_page]"; assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=Test_page\">test_page</A>\n", translate(src) ); } public void testExtraPagename2() throws Exception { String src = "Link [test.page]"; assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=Test.page\">test.page</A>\n", translate(src) ); } public void testExtraPagename3() throws Exception { String src = "Link [.testpage_]"; assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=.testpage_\">.testpage_</A>\n", translate(src) ); } public void testInlineImages() throws Exception { String src = "Link [test|http: assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http: translate(src) ); } public void testInlineImages2() throws Exception { String src = "Link [test|http: assertEquals("Link <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testInlineImages3() throws Exception { String src = "Link [test|http://images.com/testi]"; assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http://images.com/testi\" ALT=\"test\">\n", translate(src) ); } public void testInlineImages4() throws Exception { String src = "Link [test|http://foobar.jpg]"; assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http://foobar.jpg\" ALT=\"test\">\n", translate(src) ); } public void testScandicPagename1() throws Exception { String src = "Link [Test]"; assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=%C5%E4Test\">Test</A>\n", translate(src)); } public void testParagraph() throws Exception { String src = "1\n\n2\n\n3"; assertEquals( "1\n<P>\n2\n<P>\n3\n", translate(src) ); } public void testLinebreak() throws Exception { String src = "1\\\\2"; assertEquals( "1<BR>2\n", translate(src) ); } public void testTT() throws Exception { String src = "1{{2345}}6"; assertEquals( "1<TT>2345</TT>6\n", translate(src) ); } public void testTTAcrossLines() throws Exception { String src = "1{{\n2345\n}}6"; assertEquals( "1<TT>\n2345\n</TT>6\n", translate(src) ); } public void testPre() throws Exception { String src = "1{{{2345}}}6"; assertEquals( "1<PRE>2345</PRE>6\n", translate(src) ); } public void testPre2() throws Exception { String src = "1 {{{ {{{ 2345 }}} }}} 6"; assertEquals( "1 <PRE> {{{ 2345 </PRE> }}} 6\n", translate(src) ); } public void testList1() throws Exception { String src = "A list:\n* One\n* Two\n* Three\n"; assertEquals( "A list:\n<UL>\n<LI> One\n<LI> Two\n<LI> Three\n</UL>\n", translate(src) ); } /** Plain multi line testing: <pre> * One continuing * Two * Three </pre> */ public void testMultilineList1() throws Exception { String src = "A list:\n* One\n continuing.\n* Two\n* Three\n"; assertEquals( "A list:\n<UL>\n<LI> One\n continuing.\n<LI> Two\n<LI> Three\n</UL>\n", translate(src) ); } public void testMultilineList2() throws Exception { String src = "A list:\n* One\n continuing.\n* Two\n* Three\nShould be normal."; assertEquals( "A list:\n<UL>\n<LI> One\n continuing.\n<LI> Two\n<LI> Three\n</UL>\nShould be normal.\n", translate(src) ); } public void testHTML() throws Exception { String src = "<B>Test</B>"; assertEquals( "&lt;B&gt;Test&lt;/B&gt;\n", translate(src) ); } public void testHTML2() throws Exception { String src = "<P>"; assertEquals( "&lt;P&gt;\n", translate(src) ); } public void testQuotes() throws Exception { String src = "\"Test\"\""; assertEquals( "&quot;Test&quot;&quot;\n", translate(src) ); } public void testItalicAcrossLinebreak() throws Exception { String src="''This is a\ntest.''"; assertEquals( "<I>This is a\ntest.</I>\n", translate(src) ); } public void testBoldAcrossLinebreak() throws Exception { String src="__This is a\ntest.__"; assertEquals( "<B>This is a\ntest.</B>\n", translate(src) ); } public void testBoldItalic() throws Exception { String src="__This ''is'' a test.__"; assertEquals( "<B>This <I>is</I> a test.</B>\n", translate(src) ); } public void testFootnote1() throws Exception { String src="Footnote[1]"; assertEquals( "Footnote<A CLASS=\"footnoteref\" HREF=\"#ref1\">[1]</A>\n", translate(src) ); } public void testFootnote2() throws Exception { String src="[#2356] Footnote."; assertEquals( "<A CLASS=\"footnote\" NAME=\"ref2356\">[#2356]</A> Footnote.\n", translate(src) ); } /** Check an reported error condition where empty list items could cause crashes */ public void testEmptySecondLevelList() throws Exception { String src="A\n\n**\n\nB"; assertEquals( "A\n<P>\n<UL>\n<UL>\n<LI>\n</UL>\n</UL>\n<P>\nB\n", translate(src) ); } public void testEmptySecondLevelList2() throws Exception { String src="A\n\n##\n\nB"; assertEquals( "A\n<P>\n<OL>\n<OL>\n<LI>\n</OL>\n</OL>\n<P>\nB\n", translate(src) ); } public void testPluginInsert() throws Exception { String src="[{INSERT com.ecyrd.jspwiki.plugin.SamplePlugin WHERE text=test}]"; assertEquals( "test\n", translate(src) ); } public void testTable1() throws Exception { String src="|| heading || heading2 \n| Cell 1 | Cell 2 \n| Cell 3 | Cell 4\n\n"; assertEquals( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n"+ "<TR><TD CLASS=\"tablehead\"> heading <TD CLASS=\"tablehead\"> heading2 </TR>\n"+ "<TR><TD> Cell 1 <TD> Cell 2 </TR>\n"+ "<TR><TD> Cell 3 <TD> Cell 4</TR>\n"+ "</TABLE><P>\n", translate(src) ); } public void testTable2() throws Exception { String src="||heading||heading2\n|Cell 1| Cell 2\n| Cell 3 |Cell 4\n\n"; assertEquals( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n"+ "<TR><TD CLASS=\"tablehead\">heading<TD CLASS=\"tablehead\">heading2</TR>\n"+ "<TR><TD>Cell 1<TD> Cell 2</TR>\n"+ "<TR><TD> Cell 3 <TD>Cell 4</TR>\n"+ "</TABLE><P>\n", translate(src) ); } public void testTable3() throws Exception { String src="|Cell 1| Cell 2\n| Cell 3 |Cell 4\n\n"; assertEquals( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n"+ "<TR><TD>Cell 1<TD> Cell 2</TR>\n"+ "<TR><TD> Cell 3 <TD>Cell 4</TR>\n"+ "</TABLE><P>\n", translate(src) ); } public void testTableLink() throws Exception { String src="|Cell 1| Cell 2\n|[Cell 3|ReallyALink]|Cell 4\n\n"; assertEquals( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n"+ "<TR><TD>Cell 1<TD> Cell 2</TR>\n"+ "<TR><TD><A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ReallyALink\">Cell 3</A><TD>Cell 4</TR>\n"+ "</TABLE><P>\n", translate(src) ); } public static Test suite() { return new TestSuite( TranslatorReaderTest.class ); } }
package tla2sany.semantic; import java.util.Hashtable; import tla2sany.st.TreeNode; import tla2sany.utilities.Strings; public class LeafProofNode extends ProofNode { LevelNode[] facts = null ; SymbolNode[] defs = null ; boolean omitted ; boolean onlyFlag ; public LeafProofNode(TreeNode stn, LevelNode[] theFacts, SymbolNode[] theDefs, boolean omit, boolean only) { super(LeafProofKind, stn) ; this.facts = theFacts ; this.defs = theDefs ; this.omitted = omit ; this.onlyFlag = only ; } ; public LevelNode[] getFacts() {return facts ; } ; public SymbolNode[] getDefs() {return defs ;} ; public boolean getOmitted() {return omitted ;} ; public boolean getOnlyFlag() {return onlyFlag ;} ; public boolean levelCheck(int iter) { if (this.levelChecked >= iter) return this.levelCorrect; return this.levelCheckSubnodes(iter, facts) ; } public void walkGraph(Hashtable semNodesTable) { Integer uid = new Integer(myUID); if (semNodesTable.get(uid) != null) return; semNodesTable.put(new Integer(myUID), this); for (int i = 0; i < facts.length; i++) { facts[i].walkGraph(semNodesTable); } ; } public String toString(int depth) { if (depth <= 0) return ""; String ret = "\n*LeafProofNode:\n" + super.toString(depth) + Strings.indent(2, "\nfacts:") ; for (int i = 0 ; i < this.facts.length; i++) { ret += Strings.indent(4, this.facts[i].toString(depth-1)) ; } ; ret += Strings.indent(2, "\ndefs:") ; for (int i = 0 ; i < this.defs.length; i++) { ret += Strings.indent(4, this.defs[i].toString(depth-1)) ; } ; ret += Strings.indent(2, "\nomitted: " + this.omitted) + Strings.indent(2, "\nonlyFlag: " + this.onlyFlag); ret += this.getPreCommentsAsString() ; return ret; } }
import java.util.Random; import java.util.ArrayList; import java.io.FileInputStream; import java.io.*; public class Conways { private Matrixable<life> board; private boolean wraparound = true; private Integer[] born = {3}; private Integer[] survive = {2,3}; // If the rulefile passed to the constructor is valid public boolean rulesValid = true; // If there was an error when using the conways object public String error; public Conways(int r, int c, String rules) { board = new SparseMatrix<life>(r,c); if (rules != null) { byte b = loadrules(rules); if (b > 0) rulesValid = false; } } // pre: fn is a path to a file in born/survive format // post: fills the born and survive arrays private byte loadrules(String fn) { File rulesfile; FileInputStream rules; try { rulesfile = new File(fn); rules = new FileInputStream(rulesfile); } catch (Exception e) { return 1; } int c = -1; // arraylists converted back to arrays at the end ArrayList<Integer> b = new ArrayList<Integer>(); ArrayList<Integer> s = new ArrayList<Integer>(); // Where to add numbers boolean br = true; // Born/Survive for (long i = 0; i < rulesfile.length(); i++) { try { c = rules.read(); } catch(Exception e) { return 1; } if (c == '/') br = false; else { // Subtract 48 because these are raw bytes // Zero is 48 in ASCII c = c-48; if (br) { if (c >= 0) b.add(c); } else { if (c >= 0) s.add(c); } } } // Have to fill arrays because arraylist toArray doesn't work properly born = new Integer[b.size()]; for(int i = 0; i < b.size(); i++) { born[i] = (Integer)(b.get(i)); } survive = new Integer[s.size()]; for(int i = 0; i < s.size(); i++) { survive[i] = (Integer)(s.get(i)); } return 0; } // post: Advances all cells one generation public void generation() { Matrixable<life> b = board.clone(); for(int r = 0; r < board.numRows(); r++) { for(int c = 0; c < board.numColumns(); c++) { int n = livingNeighbors(b,r,c); life l = update(board.get(r,c),n); if (l != null) board.set(r,c,l); else board.remove(r,c); } } } // post: Toggles wraparound public boolean wrap() { wraparound = !wraparound; return wraparound; } public boolean getwrap() { return wraparound; } // calls other livingNeighbors with current board // see other livingNeighbors public int livingNeighbors(int r, int c) { return livingNeighbors(board,r,c); } // pre: b is a board to check, r and c are a valid location of a cell on the board // post: returns the number of neighbors a cell has private int livingNeighbors(Matrixable<life> b,int r,int c) { // Check all eight neighbors int total = 0; // The rows to be checked int[] rows = {r-1,r,r+1}; // The columns to be checked int[] cols = {c-1,c,c+1}; // If there is nothing to the left check to the right // and vice versa if (rows[0] < 0) { if (wraparound) rows[0] = b.numRows()-1; else rows[0] = -1; } if (rows[2] >= b.numRows()) { if (wraparound) rows[2] = 0; else rows[2] = -1; } if (cols[0] < 0) { if (wraparound) cols[0] = b.numColumns()-1; else cols[0] = -1; } if (cols[2] >= b.numRows()) { if(wraparound) cols[2] = 0; else cols[2] = -1; } life l; for (int i = 0; i < rows.length; i++) { for (int j = 0; j < cols.length; j++) { if (rows[i] != -1 && cols[i] != -1) l = b.get(rows[i],cols[j]); else continue; if (l != null) { if (rows[i] == r && cols[j] == c) continue; total++; } } } return total; } // pre: n is the number of neighbors a cell has // post; returns whether a cell can be born this generation public boolean isBorn(int n) { for (int i = 0; i < born.length; i++) { if (born[i] == n) return true; } return false; } // pre: n is the number of neighbors a cell has // post: returns whether a cell can survive this generation public boolean isSurvive(int n) { for (int i = 0; i < survive.length; i++) { if (survive[i] == n) return true; } return false; } // pre: l is a cell at a location, n is the number of neighbors l has // post: returns an updated version of l based on the current ruleset public life update(life l, int n) { if (l == null) { if (isBorn(n)) return new life(); return null; } else { if (isSurvive(n)) return l; return null; } } // post: the board is randomly populated with cells public void populate() { Random rand = new Random(); for (int r = 0; r < numRows(); r++) { for (int c = 0; c < numColumns(); c++) { if (rand.nextInt(10) > 5) { set(r,c,new life()); } } } } // Methods exposed from the board // See Matrixable public String toString() { return board.toString(); } public int numRows() { return board.numRows(); } public int numColumns() { return board.numColumns(); } public life set(int r, int c, life l) { return board.set(r,c,l); } public life get(int r, int c) { return board.get(r,c); } public void clear() { board.clear(); } }
import java.util.*; class VolleyTeam implements Comparable<VolleyTeam>{ private String name; private int points; private int victories; private int balance; @Override public boolean equals(Object o){ if (o == null) return false; if (!(o instanceof VolleyTeam)) return false; return ((VolleyTeam)o).name.equals(name); } public VolleyTeam(String s){ this.name=s; } public void addPoints(int i){ this.points+=i; } public void addVictory(){ victories++; } public void changeBalance(int i){ balance+=i; } public String toString(){ return this.name; } public int compareTo(VolleyTeam t){ //compares in descending order, the first has more points, more victories and/or more balance if (this.points!=t.points) return t.points-this.points; if (this.victories!=t.victories) return t.victories-this.victories; return t.balance-this.balance; } public VolleyTeam merge(VolleyTeam t){ if (this.name.equals(t.name)){ this.victories+=t.victories; this.addPoints(t.points); this.changeBalance(t.balance); return this; }else{ throw new IllegalArgumentException("Nomes diferentes para o merge"); } } } class LeagueGame{ VolleyTeam home, visitor; String homeName, visitorName; private static setLeaguePoints(VolleyTeam winner, VolleyTeam loser, int w, int l){ winner.addVictory(); if (w-l>1) winner.addPoints(3); else{ winner.addPoints(2); loser.addPoints(1); } } public LeagueGame(String s){ //get team names String[] tokens = s.split("vs"); homeName = tokens[0].trim(); tokens = tokens[1].split("/"); visitorName = tokens[0].trim(); //create teams home = new VolleyTeam(homeName); visitor = new VolleyTeam(visitorName); //get number of played sets and league points String[] sets = tokens[1].split("-"); int homeSets, visitorSets; homeSets = Integer.parseInt(sets[0]); visitorSets = Integer.parseInt(sets[1]); if (homeSets>visitorSets) setLeaguePoints(home, visitor, homeSets, visitorSets); else setLeaguePoints(visitor, home, visitorSets, homeSets); //set the balance (difference) of points for each team for(int i=2;i<tokens.length;i++){ } } } public class Counter{ public static void main(String[] args){ LeagueGame lg1 = new LeagueGame("DENTIL-PRAIA CLUBE vs CAMPONESA-MINAS/3-2/22-25/25-15/21-25/25-22/15­-12"); //System.out.println(lg1.homeName.equals(lg2.homeName)); } }
import java.util.*; import java.util.regex.*; import java.io.*; import java.lang.*; public class CSSMin { protected static boolean bDebug = false; /** * Main entry point for CSSMin from the command-line. * <b>Usage:</b> CSSMin <i>[Input file]</i>, <i>[Output file]</i>, <i>[DEBUG]</i> * @param args The command-line arguments */ public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage: "); System.out.println("CSSMin [Input file] [Output file] [DEBUG]"); System.out.println("If no output file is specified, stdout will be used."); return; } bDebug = (args.length > 2); PrintStream out; if (args.length > 1) { try { out = new PrintStream(args[1]); } catch (Exception e) { System.err.println("Error outputting to " + args[1] + "; redirecting to stdout"); out = System.out; } } else { out = System.out; } formatFile(args[0], out); } /** * Process a file from a filename. * @param filename The file name of the CSS file to process. * @param out Where to send the result */ public static void formatFile(String filename, OutputStream out) { try { formatFile(new FileReader(filename), out); } catch (java.io.FileNotFoundException e) { System.out.println(e.getMessage()); } } /** * Process input from a reader. * @param input Where to read the CSS from * @param output Where to send the result */ public static void formatFile(Reader input, OutputStream out) { formatFile(input, new PrintStream(out)); } /** * Minify CSS from a reader to a printstream. * @param input Where to read the CSS from * @param out Where to write the result to */ public static void formatFile(Reader input, PrintStream out) { try { int k, j, // Number of open braces n; // Current position in stream char curr; BufferedReader br = new BufferedReader(input); StringBuffer sb = new StringBuffer(); if (bDebug) { System.err.println("Reading file into StringBuffer..."); } String s; while ((s = br.readLine()) != null) { if (s.trim().equals("")) continue; sb.append(s); } if (bDebug) { System.err.println("Removing comments..."); } // Find the start of the comment n = 0; while ((n = sb.indexOf("/*", n)) != -1) { if (sb.charAt(n + 2) == '*') { // Retain special comments n += 2; continue; } k = sb.indexOf("*/", n + 2); if (k == -1) { throw new UnterminatedCommentException(); } sb.delete(n, k + 2); } if (bDebug) { System.err.println(sb.toString()); System.err.println("\n\n"); } if (bDebug) { System.err.println("Parsing and processing selectors..."); } Vector<Selector> selectors = new Vector<Selector>(); n = 0; j = 0; k = 0; for (int i = 0; i < sb.length(); i++) { curr = sb.charAt(i); if (j < 0) { throw new UnbalancedBracesException(); } if (curr == '{') { j++; } else if (curr == '}') { j if (j == 0) { try { selectors.addElement(new Selector(sb.substring(n, i + 1))); } catch (UnterminatedSelectorException usex) { System.out.println("Unterminated selector: " + usex.getMessage()); } catch (EmptySelectorBodyException ebex) { if (bDebug) System.out.println("Empty selector body: " + ebex.getMessage()); } n = i + 1; } } } for (Selector selector : selectors) { out.print(selector.toString()); } out.print("\r\n"); out.close(); if (bDebug) { System.err.println("Process completed successfully."); } } catch (UnterminatedCommentException ucex) { System.out.println("Unterminated comment."); } catch (UnbalancedBracesException ubex) { System.out.println("Unbalanced braces."); } catch (Exception ex) { ex.printStackTrace(System.err); System.out.println(ex.getMessage()); } } } class Selector { private Property[] properties = null; private Vector<Selector> subSelectors = null; private String selector; /** * Creates a new Selector using the supplied strings. * @param selector The selector; for example, "div { border: solid 1px red; color: blue; }" * @throws Exception If the selector is incomplete and cannot be parsed. */ public Selector(String selector) throws IncompleteSelectorException, UnterminatedSelectorException, EmptySelectorBodyException { String[] parts = selector.split("\\{"); // We have to escape the { with a \ for the regex, which itself requires escaping for the string. Sigh. if (parts.length < 2) { throw new IncompleteSelectorException(selector); } this.selector = parts[0].toString().trim(); // Simplify combinators this.selector = this.selector.replaceAll("\\s?(\\+|~|,|=|~=|\\^=|\\$=|\\*=|\\|=|>)\\s?", "$1"); // We're dealing with a nested property, eg @-webkit-keyframes if (parts.length > 2) { this.subSelectors = new Vector<Selector>(); parts = selector.split("\\{|\\}"); for (int i = 1; i < parts.length; i += 2) { parts[i] = parts[i].trim(); parts[i + 1] = parts[i + 1].trim(); if (!(parts[i].equals("") || (parts[i + 1].equals("")))) { this.subSelectors.addElement(new Selector(parts[i] + "{" + parts[i + 1] + "}")); } } } else { String contents = parts[parts.length - 1].trim(); if (CSSMin.bDebug) { System.err.println("Parsing selector: " + this.selector); System.err.println("\t" + contents); } if (contents.charAt(contents.length() - 1) != '}') { // Ensure that we have a leading and trailing brace. throw new UnterminatedSelectorException(selector); } if (contents.length() == 1) { throw new EmptySelectorBodyException(selector); } contents = contents.substring(0, contents.length() - 2); this.properties = new Property[0]; this.properties = parseProperties(contents).toArray(this.properties); sortProperties(this.properties); } } /** * Prints out this selector and its contents nicely, with the contents sorted alphabetically. * @returns A string representing this selector, minified. */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append(this.selector).append("{"); if (this.subSelectors != null) { for (Selector s : this.subSelectors) { sb.append(s.toString()); } } if (this.properties != null) { for (Property p : this.properties) { sb.append(p.toString()); } } if (sb.charAt(sb.length() - 1) == ';') { sb.deleteCharAt(sb.length() - 1); } sb.append("}"); return sb.toString(); } /** * Parses out the properties of a selector's body. * @param contents The body; for example, "border: solid 1px red; color: blue;" * @returns An array of properties parsed from this selector. */ private ArrayList<Property> parseProperties(String contents) { ArrayList<String> parts = new ArrayList<String>(); boolean bCanSplit = true; int j = 0; String substr; for (int i = 0; i < contents.length(); i++) { if (!bCanSplit) { // If we're inside a string bCanSplit = (contents.charAt(i) == '"'); } else if (contents.charAt(i) == '"') { bCanSplit = false; } else if (contents.charAt(i) == ';') { substr = contents.substring(j, i); if (!(substr.trim().equals("") || (substr == null))) parts.add(substr); j = i + 1; } } substr = contents.substring(j, contents.length()); if (!(substr.trim().equals("") || (substr == null))) parts.add(substr); ArrayList<Property> results = new ArrayList<Property>(); for (int i = 0; i < parts.size(); i++) { try { results.add(new Property(parts.get(i))); } catch (IncompletePropertyException ipex) { System.out.println("Incomplete property: " + ipex.getMessage()); } } return results; } /** * Sorts the properties array to enhance gzipping. * @param properties The array to be sorted. */ private void sortProperties(Property[] properties) { Arrays.sort(properties); } } class Property implements Comparable<Property> { protected String property; protected Part[] parts; /** * Creates a new Property using the supplied strings. Parses out the values of the property selector. * @param property The property; for example, "border: solid 1px red;" or "-moz-box-shadow: 3px 3px 3px rgba(255, 255, 0, 0.5);". * @throws Exception If the property is incomplete and cannot be parsed. */ public Property(String property) throws IncompletePropertyException { try { // Parse the property. ArrayList<String> parts = new ArrayList<String>(); boolean bCanSplit = true; int j = 0; String substr; if (CSSMin.bDebug) { System.err.println("\t\tExamining property: " + property); } for (int i = 0; i < property.length(); i++) { if (!bCanSplit) { // If we're inside a string bCanSplit = (property.charAt(i) == '"'); } else if (property.charAt(i) == '"') { bCanSplit = false; } else if (property.charAt(i) == ':') { substr = property.substring(j, i); if (!(substr.trim().equals("") || (substr == null))) parts.add(substr); j = i + 1; } } substr = property.substring(j, property.length()); if (!(substr.trim().equals("") || (substr == null))) parts.add(substr); if (parts.size() < 2) { throw new IncompletePropertyException(property); } this.property = parts.get(0).trim().toLowerCase(); this.parts = parseValues(simplifyColours(parts.get(1).trim().replaceAll(", ", ","))); } catch (PatternSyntaxException e) { // Invalid regular expression used. } } /** * Prints out this property nicely. * @returns A string representing this property, minified. */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append(this.property).append(":"); for (Part p : this.parts) { sb.append(p.toString()).append(","); } sb.deleteCharAt(sb.length() - 1); // Delete the trailing comma. sb.append(";"); if (CSSMin.bDebug) { System.err.println(sb.toString()); } return sb.toString(); } /** * Compare this property with another. */ public int compareTo(Property other) { // We can't just use String.compareTo(), because we need to sort properties that have hack prefixes last -- eg, *display should come after display. String thisProp = this.property; String thatProp = other.property; String[] parts; if (thisProp.charAt(0) == '-') { thisProp = thisProp.substring(1); thisProp = thisProp.substring(thisProp.indexOf('-') + 1); } else if (thisProp.charAt(0) < 65) { thisProp = thisProp.substring(1); } if (thatProp.charAt(0) == '-') { thatProp = thatProp.substring(1); thatProp = thatProp.substring(thatProp.indexOf('-') + 1); } else if (thatProp.charAt(0) < 65) { thatProp = thatProp.substring(1); } return thisProp.compareTo(thatProp); } /** * Parse the values out of a property. * @param contents The property to parse * @returns An array of Parts */ private Part[] parseValues(String contents) { String[] parts = contents.split(","); Part[] results = new Part[parts.length]; for (int i = 0; i < parts.length; i++) { try { results[i] = new Part(parts[i], property); } catch (Exception e) { System.out.println(e.getMessage()); results[i] = null; } } return results; } private String simplifyColours(String contents) { // This replacement, although it results in a smaller uncompressed file, // actually makes the gzipped file bigger -- people tend to use rgba(0,0,0,0.x) // quite a lot, which means that rgba(0,0,0,0) has its first eight or so characters // compressed really efficiently; much more so than "transparent". //contents = contents.replaceAll("rgba\\(0,0,0,0\\)", "transparent"); return simplifyRGBColours(contents); } // Convert rgb(51,102,153) to #336699 (this code largely based on YUI code) private String simplifyRGBColours(String contents) { StringBuffer newContents = new StringBuffer(); StringBuffer hexColour; String[] rgbColours; int colourValue; Pattern pattern = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)"); Matcher matcher = pattern.matcher(contents); while (matcher.find()) { hexColour = new StringBuffer(" rgbColours = matcher.group(1).split(","); for (int i = 0; i < rgbColours.length; i++) { colourValue = Integer.parseInt(rgbColours[i]); if (colourValue < 16) { hexColour.append("0"); } hexColour.append(Integer.toHexString(colourValue)); } matcher.appendReplacement(newContents, hexColour.toString()); } matcher.appendTail(newContents); return newContents.toString(); } } class Part { String contents; String property; /** * Create a new property by parsing the given string. * @param contents The string to parse. * @throws Exception If the part cannot be parsed. */ public Part(String contents, String property) throws Exception { // Many of these regular expressions are adapted from those used in the YUI CSS Compressor. // For simpler regexes. this.contents = " " + contents; this.property = property; simplify(); } private void simplify() { // !important doesn't need to be spaced this.contents = this.contents.replaceAll(" !important", "!important"); // Replace 0in, 0cm, etc. with just 0 this.contents = this.contents.replaceAll("(\\s)(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2"); // Replace 0.6 with .6 // Disabled, as it actually makes compression worse! People use rgba(0,0,0,0) and rgba(0,0,0,0.x) a lot. //this.contents = this.contents.replaceAll("(\\s)0+\\.(\\d+)", "$1.$2"); this.contents = this.contents.trim(); // Simplify multiple zeroes if (this.contents.equals("0 0 0 0")) this.contents = "0"; if (this.contents.equals("0 0 0")) this.contents = "0"; if (this.contents.equals("0 0")) this.contents = "0"; // Simplify multiple-parameter properties simplifyParameters(); // Simplify font weights simplifyFontWeights(); // Strip unnecessary quotes from url() and single-word parts, and make as much lowercase as possible. simplifyQuotesAndCaps(); // Simplify colours simplifyColourNames(); simplifyHexColours(); } private void simplifyParameters() { StringBuffer newContents = new StringBuffer(); String[] params = this.contents.split(" "); if (params.length == 4) { // We can drop off the fourth item if the second and fourth items match // ie turn 3px 0 3px 0 into 3px 0 3px if (params[1].equalsIgnoreCase(params[3])) { params = Arrays.copyOf(params, 3); } } if (params.length == 3) { // We can drop off the third item if the first and third items match // ie turn 3px 0 3px into 3px 0 if (params[0].equalsIgnoreCase(params[2])) { params = Arrays.copyOf(params, 2); } } if (params.length == 2) { // We can drop off the second item if the first and second items match // ie turn 3px 3px into 3px if (params[0].equalsIgnoreCase(params[1])) { params = Arrays.copyOf(params, 1); } } for (int i = 0; i < params.length; i++) { newContents.append(params[i] + " "); } newContents.deleteCharAt(newContents.length() - 1); // Delete the trailing space this.contents = newContents.toString(); } private void simplifyFontWeights() { if (!this.property.equals("font-weight")) return; String lcContents = this.contents.toLowerCase(); for (int i = 0; i < Constants.fontWeightNames.length; i++) { if (lcContents.equals(Constants.fontWeightNames[i])) { this.contents = Constants.fontWeightValues[i]; break; } } } private void simplifyQuotesAndCaps() { // Strip quotes from URLs if ((this.contents.length() > 4) && (this.contents.substring(0, 4).equalsIgnoreCase("url("))) { this.contents = this.contents.replaceAll("(?i)url\\(('|\")?(.*?)\\1\\)", "url($2)"); } else { String[] words = this.contents.split("\\s"); if (words.length == 1) { this.contents = this.contents.toLowerCase(); this.contents = this.contents.replaceAll("('|\")?(.*?)\1", "$2"); } } } private void simplifyColourNames() { String lcContents = this.contents.toLowerCase(); for (int i = 0; i < Constants.htmlColourNames.length; i++) { if (lcContents.equals(Constants.htmlColourNames[i])) { if (Constants.htmlColourValues[i].length() < Constants.htmlColourNames[i].length()) { this.contents = Constants.htmlColourValues[i]; } break; } else if (lcContents.equals(Constants.htmlColourValues[i])) { if (Constants.htmlColourNames[i].length() < Constants.htmlColourValues[i].length()) { this.contents = Constants.htmlColourNames[i]; } } } } private void simplifyHexColours() { StringBuffer newContents = new StringBuffer(); Pattern pattern = Pattern.compile("#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])"); Matcher matcher = pattern.matcher(this.contents); while (matcher.find()) { if (matcher.group(1).equalsIgnoreCase(matcher.group(2)) && matcher.group(3).equalsIgnoreCase(matcher.group(4)) && matcher.group(5).equalsIgnoreCase(matcher.group(6))) { matcher.appendReplacement(newContents, "#" + matcher.group(1).toLowerCase() + matcher.group(3).toLowerCase() + matcher.group(5).toLowerCase()); } else { matcher.appendReplacement(newContents, matcher.group().toLowerCase()); } } matcher.appendTail(newContents); this.contents = newContents.toString(); } /** * Returns itself. * @returns this part's string representation. */ public String toString() { return this.contents; } } class UnterminatedCommentException extends Exception {} class UnbalancedBracesException extends Exception {} class IncompletePropertyException extends Exception { String message = null; public IncompletePropertyException(String message) { this.message = message; } public String getMessage() { return this.message; } } class EmptySelectorBodyException extends Exception { String message = null; public EmptySelectorBodyException(String message) { this.message = message; } public String getMessage() { return this.message; } } class UnterminatedSelectorException extends Exception { String message = null; public UnterminatedSelectorException(String message) { this.message = message; } public String getMessage() { return this.message; } } class IncompleteSelectorException extends Exception { String message = null; public IncompleteSelectorException(String message) { this.message = message; } public String getMessage() { return this.message; } } class Constants { static final String[] htmlColourNames = { "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", "goldenrod", "gray", "green", "greenyellow", "honeydew", "hotpink", "indianred ", "indigo ", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgrey", "lightgreen", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen" }; static final String[] htmlColourValues = { "#f0f8ff", "#faebd7", "#00ffff", "#7fffd4", "#f0ffff", "#f5f5dc", "#ffe4c4", "#000", "#ffebcd", "#00f", "#8a2be2", "#a52a2a", "#deb887", "#5f9ea0", "#7fff00", "#d2691e", "#ff7f50", "#6495ed", "#fff8dc", "#dc143c", "#0ff", "#00008b", "#008b8b", "#b8860b", "#a9a9a9", "#006400", "#bdb76b", "#8b008b", "#556b2f", "#ff8c00", "#9932cc", "#8b0000", "#e9967a", "#8fbc8f", "#483d8b", "#2f4f4f", "#00ced1", "#9400d3", "#ff1493", "#00bfff", "#696969", "#1e90ff", "#b22222", "#fffaf0", "#228b22", "#f0f", "#dcdcdc", "#f8f8ff", "#ffd700", "#daa520", "#808080", "#008000", "#adff2f", "#f0fff0", "#ff69b4", "#cd5c5c", "#4b0082", "#fffff0", "#f0e68c", "#e6e6fa", "#fff0f5", "#7cfc00", "#fffacd", "#add8e6", "#f08080", "#e0ffff", "#fafad2", "#d3d3d3", "#90ee90", "#ffb6c1", "#ffa07a", "#20b2aa", "#87cefa", "#789", "#b0c4de", "#ffffe0", "#0f0", "#32cd32", "#faf0e6", "#f0f", "#800000", "#66cdaa", "#0000cd", "#ba55d3", "#9370d8", "#3cb371", "#7b68ee", "#00fa9a", "#48d1cc", "#c71585", "#191970", "#f5fffa", "#ffe4e1", "#ffe4b5", "#ffdead", "#000080", "#fdf5e6", "#808000", "#6b8e23", "#ffa500", "#ff4500", "#da70d6", "#eee8aa", "#98fb98", "#afeeee", "#d87093", "#ffefd5", "#ffdab9", "#cd853f", "#ffc0cb", "#dda0dd", "#b0e0e6", "#800080", "#f00", "#bc8f8f", "#4169e1", "#8b4513", "#fa8072", "#f4a460", "#2e8b57", "#fff5ee", "#a0522d", "#c0c0c0", "#87ceeb", "#6a5acd", "#708090", "#fffafa", "#00ff7f", "#4682b4", "#d2b48c", "#008080", "#d8bfd8", "#ff6347", "#40e0d0", "#ee82ee", "#f5deb3", "#fff", "#f5f5f5", "#ff0", "#9acd32" }; static final String[] fontWeightNames = { "normal", "bold", "bolder", "lighter" }; static final String[] fontWeightValues = { "400", "700", "900", "100" }; }
public class Calcpi { public static void main(String[] args) { double x, y; int insideCircle = 0, total = 999999;//Integer.MAX_VALUE; //MAX_VALUE will need a lots of time but will yeild better result for (int i = 0; i < total; i++) { x = Math.random(); y = Math.random(); if (x * x + y * y <= 1){ insideCircle++; System.out.print("Calculating pi "+Math.round((100.0*i)/total)+"%\r"); } } System.out.println("\n"+(4.0 * insideCircle / total)+" as i calculated"); System.out.println(Math.PI+" as the system uses"); } }
package nl.mpi.arbil; import javax.swing.SwingUtilities; public class ArbilApplet extends javax.swing.JApplet { public void init() { //System.setProperty("sun.swing.enableImprovedDragGesture", "true"); try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { mainSplitPane = new javax.swing.JSplitPane(); getContentPane().add(mainSplitPane, java.awt.BorderLayout.CENTER); previewSplitPanel = new PreviewSplitPanel(); mainSplitPane.setRightComponent(previewSplitPanel); arbilTreePanels = new ArbilTreePanels(); mainSplitPane.setLeftComponent(arbilTreePanels); previewSplitPanel.setPreviewPanel(true); ArbilMenuBar arbilMenuBar = new ArbilMenuBar(previewSplitPanel, ArbilApplet.this); setJMenuBar(arbilMenuBar); // LinorgWindowManager.getSingleInstance().setComponents(this); LinorgWindowManager.getSingleInstance().openIntroductionPage(); arbilTreePanels.setDefaultTreePaneSize(); previewSplitPanel.setDividerLocation(0.3); } }); } catch (Exception ex) { new LinorgBugCatcher().logError(ex); } } public void start() { } private javax.swing.JSplitPane mainSplitPane; private nl.mpi.arbil.ArbilTreePanels arbilTreePanels; private nl.mpi.arbil.PreviewSplitPanel previewSplitPanel; }
package com.krishagni.catissueplus.core.de.events; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.krishagni.catissueplus.core.de.domain.DeObject; import com.krishagni.catissueplus.core.de.domain.DeObject.Attr; public class ExtensionDetail implements Serializable { private Long id; private Long objectId; private Long formId; private String formCaption; private List<AttrDetail> attrs = new ArrayList<>(); private Map<String, Object> attrsMap; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getObjectId() { return objectId; } public void setObjectId(Long objectId) { this.objectId = objectId; } public Long getFormId() { return formId; } public void setFormId(Long formId) { this.formId = formId; } public String getFormCaption() { return formCaption; } public void setFormCaption(String formCaption) { this.formCaption = formCaption; } public List<AttrDetail> getAttrs() { return attrs; } public void setAttrs(List<AttrDetail> attrs) { this.attrs = attrs; this.attrsMap = null; } @JsonProperty public void setAttrsMap(Map<String, Object> attrsMap) { attrs.clear(); for (Map.Entry<String, Object> entry : attrsMap.entrySet()) { AttrDetail attr = new AttrDetail(); attr.setName(entry.getKey()); attr.setValue(entry.getValue()); attrs.add(attr); } this.attrsMap = null; } @JsonIgnore public Map<String, Object> getAttrsMap() { if (attrsMap == null) { attrsMap = getAttrsMap(attrs); } return attrsMap; } public static ExtensionDetail from(DeObject extension) { return from(extension, true); } public static ExtensionDetail from(DeObject extension, boolean excludePhi) { return from(extension, excludePhi, false); } public static ExtensionDetail from(DeObject extension, boolean excludePhi, boolean lenient) { if (extension == null || (!lenient && extension.getId() == null)) { return null; } ExtensionDetail detail = new ExtensionDetail(); detail.setId(extension.getId()); detail.setObjectId(extension.getObjectId()); detail.setFormId(extension.getFormId()); detail.setFormCaption(extension.getFormCaption()); detail.setAttrs(AttrDetail.from(extension.getAttrs(), excludePhi)); return detail; } private static Map<String, Object> getAttrsMap(List<AttrDetail> attrs) { Map<String, Object> attrsMap = new HashMap<>(); for (AttrDetail attr : attrs) { if ("subForm".equals(attr.getType())) { List value = (List) attr.getValue(); if (CollectionUtils.isEmpty(value)) { continue; } if (value.get(0) instanceof AttrDetail) { attrsMap.put(attr.getName(), getAttrsMap((List<AttrDetail>) value)); } else if (value.get(0) instanceof List) { List<Map<String, Object>> sfAttrsMap = ((List<List<AttrDetail>>) value).stream() .map(ExtensionDetail::getAttrsMap).collect(Collectors.toList()); attrsMap.put(attr.getName(), sfAttrsMap); } } else if ("fileUpload".equals(attr.getType()) || attr.getValue() instanceof List) { attrsMap.put(attr.getName(), attr.getValue()); } else { Object value = attr.getDisplayValue(); if (value == null) { value = attr.getValue(); } attrsMap.put(attr.getName(), value); } } return attrsMap; } public static class AttrDetail implements Serializable { private String name; private String udn; private String caption; private Object value; private String type; private String displayValue; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUdn() { return udn; } public void setUdn(String udn) { this.udn = udn; } public String getCaption() { return caption; } public void setCaption(String caption) { this.caption = caption; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDisplayValue() { return displayValue; } public void setDisplayValue(String displayValue) { this.displayValue = displayValue; } @SuppressWarnings({"unchecked" }) public static AttrDetail from(Attr attr, boolean excludePhi) { AttrDetail detail = new AttrDetail(); detail.setName(attr.getName()); detail.setUdn(attr.getUdn()); detail.setCaption(attr.getCaption()); detail.setType(attr.getType()); if (attr.isSubForm()) { if (attr.isOneToOne()) { detail.setValue(from((List)attr.getValue(), excludePhi)); } else { List<List<Attr>> sfAttrs = (List<List<Attr>>) attr.getValue(); if (sfAttrs != null) { detail.setValue(sfAttrs.stream().map(sfAttr -> from(sfAttr, excludePhi)).collect(Collectors.toList())); } } } else if (excludePhi && attr.isPhi()) { detail.setValue(" detail.setDisplayValue(" } else { detail.setValue(attr.getValue()); detail.setDisplayValue(attr.getDisplayValue()); } return detail; } public static List<AttrDetail> from(List<Attr> attrs, boolean excludePhi) { return attrs.stream().map(attr -> from(attr, excludePhi)).collect(Collectors.toList()); } } }
package edu.wustl.catissuecore.interceptor; import java.util.ArrayList; import java.util.List; import edu.wustl.catissuecore.domain.Specimen; import edu.wustl.catissuecore.interceptor.wmq.SpecimenWmqProcessor; import edu.wustl.common.bizlogic.DefaultBizLogic; import edu.wustl.common.exception.BizLogicException; import edu.wustl.common.util.XMLPropertyHandler; import edu.wustl.common.util.global.CommonServiceLocator; import edu.wustl.common.util.logger.Logger; import edu.wustl.common.util.logger.LoggerConfig; import edu.wustl.dao.JDBCDAO; import edu.wustl.dao.daofactory.DAOConfigFactory; import edu.wustl.dao.exception.DAOException; import edu.wustl.dao.interceptor.SaveUpdateInterceptThread.eventType; import edu.wustl.dao.query.generator.ColumnValueBean; public class SpecimenDataBackloader { static { LoggerConfig.configureLogger(System.getProperty("user.dir")); } private static final Logger LOGGER = Logger.getCommonLogger(SpecimenDataBackloader.class); private static final String SPECIMEN_ID_QUERY = "select specimen.identifier from catissue_specimen specimen " +"join catissue_specimen_coll_group scg on scg.identifier = specimen.specimen_collection_group_id and specimen.collection_status = 'Collected' " +"join catissue_coll_prot_reg cpr on cpr.identifier = scg.collection_protocol_reg_id " +"join catissue_collection_protocol cp on cp.identifier = cpr.collection_protocol_id and cp.is_empi_enable = 1 " +"join catissue_specimen_protocol sp on sp.identifier = cp.identifier and sp.short_title like ? " +"join catissue_participant participant on participant.identifier = cpr.participant_id and participant.empi_id is not null"; /** * This method called to get JDBCDAO instance. * @return JDBCDAO instance. * @throws BizLogicException BizLogicException */ protected JDBCDAO openJDBCSession() throws DAOException { JDBCDAO jdbcDAO = null; final String applicationName = CommonServiceLocator.getInstance().getAppName(); jdbcDAO = DAOConfigFactory.getInstance().getDAOFactory(applicationName).getJDBCDAO(); jdbcDAO.openSession(null); return jdbcDAO; } /** * This method called to close JDBC session. * @param jdbcDAO jdbcDAO * @throws BizLogicException BizLogicException */ protected void closeJDBCSession(JDBCDAO jdbcDAO) throws DAOException { if (jdbcDAO != null) { jdbcDAO.closeSession(); } } public void sendOldSpeciemnDataToCider(String cpShortTitle) { final String path = System.getProperty("app.propertiesFile"); try { XMLPropertyHandler.init(path); LOGGER.info("sysout WMQ initialazation in progress"); SpecimenWmqProcessor.getInstance(); //fetch all the specimens which are in collected state List<Long> specimenIdList = getSpecimenIdentifiersList(cpShortTitle); final DefaultBizLogic bizLogic = new DefaultBizLogic(); LOGGER.info("Number of Specimen's in backLoad " + specimenIdList.size()); SpecimenInterceptor interceptor = new SpecimenInterceptor(); //iterate on each specimen & then send the information to the CIDER using specimen Interceptor. for(Long specimenId : specimenIdList) { LOGGER.info("Processing Specimen with ID "+specimenId); Specimen specimen =(Specimen) bizLogic.retrieve(Specimen.class.getName(), specimenId); interceptor.process(specimen, eventType.onInsert); } } catch (Exception e) { LOGGER.error("Error occured while processing the specimens",e); } } private List<Long> getSpecimenIdentifiersList(String cpShortTitle) throws DAOException { String shortTitle; final List<Long> specimenIdList = new ArrayList<Long>(); if(cpShortTitle!=null && !"".equals(cpShortTitle)) { shortTitle = cpShortTitle; } else { shortTitle="%"; } JDBCDAO dao = null; try { dao = openJDBCSession(); List<ColumnValueBean> colValueBeanList = new ArrayList<ColumnValueBean>(); colValueBeanList.add(new ColumnValueBean("SHORT_TITLE", shortTitle)); System.out.println("short title : "+shortTitle); final List<List<String>> resultList = dao.executeQuery(SPECIMEN_ID_QUERY, colValueBeanList); for(List<String> recordList : resultList) { specimenIdList.add(Long.parseLong(recordList.get(0))); } } finally { closeJDBCSession(dao); } LOGGER.info("Specimen data backload completed successfully."); return specimenIdList; } public static void main(String[] args) { // System.setProperty("app.propertiesDir", "./catissuecore-properties"); //System.setProperty("app.propertiesFile", "./catissuecore-properties/caTissueCore_Properties.xml"); String cpShortTitle = null; if(args.length>=1 && !"".equals(args[0].trim())) { cpShortTitle = args[0]; } SpecimenDataBackloader dataSender = new SpecimenDataBackloader(); dataSender.sendOldSpeciemnDataToCider(cpShortTitle); } }
package org.springframework.roo.addon.gwt; import java.io.FileReader; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.transform.Transformer; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.springframework.roo.addon.entity.EntityMetadata; import org.springframework.roo.classpath.PhysicalTypeCategory; import org.springframework.roo.classpath.PhysicalTypeIdentifier; import org.springframework.roo.classpath.PhysicalTypeIdentifierNamingUtils; import org.springframework.roo.classpath.details.BeanInfoUtils; import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails; import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetailsBuilder; import org.springframework.roo.classpath.details.FieldMetadata; import org.springframework.roo.classpath.details.MethodMetadata; import org.springframework.roo.classpath.details.MethodMetadataBuilder; import org.springframework.roo.classpath.details.annotations.AnnotatedJavaType; import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue; import org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder; import org.springframework.roo.classpath.details.annotations.StringAttributeValue; import org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder; import org.springframework.roo.metadata.AbstractMetadataItem; import org.springframework.roo.metadata.MetadataIdentificationUtils; import org.springframework.roo.model.DataType; import org.springframework.roo.model.JavaSymbolName; import org.springframework.roo.model.JavaType; import org.springframework.roo.project.Path; import org.springframework.roo.project.ProjectMetadata; import org.springframework.roo.support.util.Assert; import org.springframework.roo.support.util.StringUtils; import org.springframework.roo.support.util.TemplateUtils; import org.springframework.roo.support.util.XmlUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Metadata for GWT. * * @author Ben Alex * @author Alan Stewart * @author Ray Cromwell * @author Amit Manjhi * @since 1.1 */ public class GwtMetadata extends AbstractMetadataItem { private static final String PROVIDES_TYPE_STRING = GwtMetadata.class.getName(); private static final String PROVIDES_TYPE = MetadataIdentificationUtils.create(PROVIDES_TYPE_STRING); private EntityMetadata entityMetadata; private MethodMetadata findAllMethod; private MethodMetadata findMethod; private MethodMetadata countMethod; private MethodMetadata findEntriesMethod; private List<MethodMetadata> proxyMethods; private List<MethodMetadata> requestMethods; private ClassOrInterfaceTypeDetails governorTypeDetails; private ProjectMetadata projectMetadata; public GwtMetadata(String identifier, ClassOrInterfaceTypeDetails governorTypeDetails, ProjectMetadata projectMetadata, List<MethodMetadata> proxyMethods, List<MethodMetadata> requestMethods, EntityMetadata entityMetadata) { super(identifier); Assert.notNull(governorTypeDetails, "Governor details are required"); Assert.notNull(projectMetadata, "ProjectMetadata is required"); Assert.notNull(proxyMethods, "Proxy methods are required"); Assert.notNull(requestMethods, "Request methods are required"); Assert.notNull(entityMetadata, "Entity Metadata is required"); this.governorTypeDetails = governorTypeDetails; this.projectMetadata = projectMetadata; this.proxyMethods = proxyMethods; this.requestMethods = requestMethods; this.entityMetadata = entityMetadata; resolveEntityInformation(); } private void resolveEntityInformation() { if (entityMetadata == null || !entityMetadata.isValid()) { return; } // Lookup special fields String typeName = governorTypeDetails.getName().getFullyQualifiedTypeName(); FieldMetadata idField = entityMetadata.getIdentifierField(); Assert.notNull(idField, "GWT support requires an @Id field for " + typeName); FieldMetadata versionField = entityMetadata.getVersionField(); Assert.notNull(versionField, "GWT support requires an @Version field for " + typeName); JavaSymbolName versionPropertyName = versionField.getFieldName(); Assert.isTrue("version".equals(versionPropertyName.getSymbolName()), "GWT support requires that an @Version field be named \"version\" (found \"" + versionPropertyName + "\") for " + typeName); // Lookup the find and count methods and store them findAllMethod = entityMetadata.getFindAllMethod(); Assert.notNull(findAllMethod, "GWT support requires a findAll method for " + typeName); findMethod = entityMetadata.getFindMethod(); Assert.notNull(findMethod, "GWT support requires a find method for " + typeName); findEntriesMethod = entityMetadata.getFindEntriesMethod(); Assert.notNull(findEntriesMethod, "GWT support requires a findEntries method for " + typeName); countMethod = entityMetadata.getCountMethod(); Assert.notNull(countMethod, "GWT support requires a count method for " + typeName); } public ClassOrInterfaceTypeDetails buildProxy() { String destinationMetadataId = getDestinationMetadataId(GwtType.PROXY); // Get the proxy's PhysicalTypeMetaData representation of the on disk proxy JavaType name = PhysicalTypeIdentifier.getJavaType(destinationMetadataId); // Create a new ClassOrInterfaceTypeDetailsBuilder for the Proxy, will be overridden if the Proxy has already been created ClassOrInterfaceTypeDetailsBuilder typeDetailsBuilder = new ClassOrInterfaceTypeDetailsBuilder(destinationMetadataId, Modifier.PUBLIC, name, PhysicalTypeCategory.INTERFACE); List<AnnotationMetadataBuilder> typeAnnotations = createAnnotations(); // Add @ProxyForName("com.foo.bar.Foo") annotation typeAnnotations.add(createAdditionalAnnotation(new JavaType("com.google.gwt.requestfactory.shared.ProxyForName"))); // Only add annotations that don't already exist on the target for (AnnotationMetadataBuilder annotationBuilder : typeAnnotations) { boolean exists = false; for (AnnotationMetadataBuilder existingAnnotation : typeDetailsBuilder.getAnnotations()) { if (existingAnnotation.getAnnotationType().equals(annotationBuilder.getAnnotationType())) { exists = true; break; } } if (!exists) { typeDetailsBuilder.addAnnotation(annotationBuilder); } } // Only inherit from EntityProxy if extension is not already defined if (!typeDetailsBuilder.getExtendsTypes().contains(new JavaType("com.google.gwt.requestfactory.shared.EntityProxy"))) { typeDetailsBuilder.addExtendsTypes(new JavaType("com.google.gwt.requestfactory.shared.EntityProxy")); } List<MethodMetadataBuilder> methods = new LinkedList<MethodMetadataBuilder>(); for (MethodMetadata method : proxyMethods) { MethodMetadataBuilder abstractAccessorMethodBuilder = new MethodMetadataBuilder(destinationMetadataId, method); abstractAccessorMethodBuilder.setBodyBuilder(new InvocableMemberBodyBuilder()); abstractAccessorMethodBuilder.setModifier(Modifier.ABSTRACT); methods.add(abstractAccessorMethodBuilder); String propertyName = method.getMethodName().getSymbolName().replaceFirst("get", ""); MethodMetadataBuilder abstractMutatorMethodBuilder = new MethodMetadataBuilder(destinationMetadataId, method); abstractMutatorMethodBuilder.setBodyBuilder(new InvocableMemberBodyBuilder()); abstractMutatorMethodBuilder.setModifier(Modifier.ABSTRACT); abstractMutatorMethodBuilder.setReturnType(JavaType.VOID_PRIMITIVE); abstractMutatorMethodBuilder.setParameterTypes(AnnotatedJavaType.convertFromJavaTypes(Arrays.asList(method.getReturnType()))); abstractMutatorMethodBuilder.setParameterNames(Arrays.asList(new JavaSymbolName(StringUtils.uncapitalize(propertyName)))); abstractMutatorMethodBuilder.setMethodName(new JavaSymbolName(method.getMethodName().getSymbolName().replaceFirst("get", "set"))); methods.add(abstractMutatorMethodBuilder); } typeDetailsBuilder.setDeclaredMethods(methods); return typeDetailsBuilder.build(); } public ClassOrInterfaceTypeDetails buildRequest() { String destinationMetadataId = getDestinationMetadataId(GwtType.REQUEST); JavaType name = PhysicalTypeIdentifier.getJavaType(destinationMetadataId); List<AnnotationMetadataBuilder> typeAnnotations = createAnnotations(); // @Service(Employee.class) typeAnnotations.add(createAdditionalAnnotation(new JavaType("com.google.gwt.requestfactory.shared.ServiceName"))); List<MethodMetadataBuilder> methods = new LinkedList<MethodMetadataBuilder>(); for (MethodMetadata method : requestMethods) { methods.add(getRequestMethod(destinationMetadataId, method)); } List<JavaType> extendsTypes = Collections.singletonList(new JavaType("com.google.gwt.requestfactory.shared.RequestContext")); ClassOrInterfaceTypeDetailsBuilder typeDetailsBuilder = new ClassOrInterfaceTypeDetailsBuilder(destinationMetadataId, Modifier.PUBLIC, name, PhysicalTypeCategory.INTERFACE); typeDetailsBuilder.setAnnotations(typeAnnotations); typeDetailsBuilder.setDeclaredMethods(methods); typeDetailsBuilder.setExtendsTypes(extendsTypes); return typeDetailsBuilder.build(); } public String buildUiXml(String templateContents, String destFile) { try { Transformer transformer = XmlUtils.createIndentingTransformer(); DocumentBuilder builder = XmlUtils.getDocumentBuilder(); builder.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (systemId.equals("http://dl.google.com/gwt/DTD/xhtml.ent")) { return new InputSource(TemplateUtils.getTemplate(GwtMetadata.class, "templates/xhtml.ent")); } else { // Use the default behaviour return null; } } }); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(templateContents)); Document templateDocument = builder.parse(is); is = new InputSource(); is.setCharacterStream(new FileReader(destFile)); Document existingDocument = builder.parse(is); /** * @param gwtType the mirror class we're producing (required) * @return the MID to the mirror class applicable for the current governor (never null) */ private String getDestinationMetadataId(GwtType gwtType) { return PhysicalTypeIdentifier.createIdentifier(GwtUtils.convertGovernorTypeNameIntoKeyTypeName(gwtType, projectMetadata, governorTypeDetails.getName()), Path.SRC_MAIN_JAVA); } /** * @param gwtType the mirror class we're producing (required) * @return the Java type the mirror class applicable for the current governor (never null) */ @SuppressWarnings("unused") private JavaType getDestinationJavaType(GwtType gwtType) { return PhysicalTypeIdentifier.getJavaType(getDestinationMetadataId(gwtType)); } private AnnotationMetadataBuilder createAdditionalAnnotation(JavaType serverType) { List<AnnotationAttributeValue<?>> serverTypeAttributes = new ArrayList<AnnotationAttributeValue<?>>(); serverTypeAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), governorTypeDetails.getName().getFullyQualifiedTypeName())); return new AnnotationMetadataBuilder(serverType, serverTypeAttributes); } /** * @return a newly-created type annotations list, complete with the @RooGwtMirroredFrom annotation properly setup */ private List<AnnotationMetadataBuilder> createAnnotations() { List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); List<AnnotationAttributeValue<?>> rooGwtMirroredFromConfig = new ArrayList<AnnotationAttributeValue<?>>(); rooGwtMirroredFromConfig.add(new StringAttributeValue(new JavaSymbolName("value"), governorTypeDetails.getName().getFullyQualifiedTypeName())); annotations.add(new AnnotationMetadataBuilder(new JavaType(RooGwtMirroredFrom.class.getName()), rooGwtMirroredFromConfig)); return annotations; } public static String getMetadataIdentifierType() { return PROVIDES_TYPE; } public static String createIdentifier(JavaType javaType, Path path) { return PhysicalTypeIdentifierNamingUtils.createIdentifier(PROVIDES_TYPE_STRING, javaType, path); } public static JavaType getJavaType(String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getJavaType(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static Path getPath(String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getPath(PROVIDES_TYPE_STRING, metadataIdentificationString); } }
package org.apache.fop.fo; // FOP import org.apache.fop.layout.FontState; import org.apache.fop.layout.*; import org.apache.fop.datatypes.*; import org.apache.fop.fo.properties.*; import org.apache.fop.apps.FOPException; import org.apache.fop.layoutmgr.LayoutManager; import org.apache.fop.layoutmgr.TextBPLayoutManager; import org.apache.fop.apps.StructureHandler; import java.util.NoSuchElementException; import java.util.List; public class FOText extends FObj { protected char[] ca; protected int start; protected int length; TextInfo textInfo; TextState ts; public FOText(char[] chars, int s, int e, TextInfo ti) { super(null); this.start = 0; this.ca = new char[e - s]; System.arraycopy(chars, s, ca, 0, e - s); this.length = e - s; textInfo = ti; } public void setStructHandler(StructureHandler st) { super.setStructHandler(st); structHandler.characters(ca, start, length); } public boolean willCreateArea() { if (textInfo.whiteSpaceCollapse == WhiteSpaceCollapse.FALSE && length > 0) { return true; } for (int i = start; i < start + length; i++) { char ch = ca[i]; if (!((ch == ' ') || (ch == '\n') || (ch == '\r') || (ch == '\t'))) { // whitespace return true; } } return false; } public void addLayoutManager(List list) { // if nothing left (length=0)? if(length == 0) return; if (length < ca.length) { char[] tmp = ca; ca = new char[length]; System.arraycopy(tmp, 0, ca, 0, length); } list.add(new TextBPLayoutManager(this, ca, textInfo)); } public CharIterator charIterator() { return new TextCharIterator(); } private class TextCharIterator extends AbstractCharIterator { int curIndex = 0; public boolean hasNext() { return (curIndex < length); } public char nextChar() { if (curIndex < length) { // Just a char class? Don't actually care about the value! return ca[curIndex++]; } else throw new NoSuchElementException(); } public void remove() { if (curIndex > 0 && curIndex < length) { // copy from curIndex to end to curIndex-1 System.arraycopy(ca, curIndex, ca, curIndex - 1, length - curIndex); length curIndex } else if (curIndex == length) { curIndex = --length; } } public void replaceChar(char c) { if (curIndex > 0 && curIndex <= length) { ca[curIndex - 1] = c; } } } }
package org.exist.xmldb; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.exist.collections.CollectionConfigurationManager; import org.exist.storage.DBBroker; import org.exist.xquery.Constants; import org.exist.xquery.util.URIUtils; import org.exist.xquery.value.AnyURIValue; /** A utility class for xmldb URis. * Since, java.net.URI is <strong>final</strong> this class acts as a wrapper. * @author Pierrick Brihaye <pierrick.brihaye@free.fr> */ /* * This base class implementation only provides a path. FullXmldbURI provides * full uri support. The create method creates a minimal object to keep memory * usage low. */ public class XmldbURI implements Comparable { protected final static Logger LOG = Logger.getLogger(DBBroker.class); public static final int NO_PORT = -1; //Should be provided by org.xmldb.api package !!! public static final String XMLDB_SCHEME = "xmldb"; public static final String XMLDB_URI_PREFIX = "xmldb:"; public static final String DEFAULT_INSTANCE_NAME = "exist"; public static final String EMBEDDED_SERVER_AUTHORITY = "embedded-eXist-server"; public final static XmldbURI ROOT_COLLECTION_URI = create(DBBroker.ROOT_COLLECTION); public final static XmldbURI RELATIVE_ROOT_COLLECTION_URI = create(DBBroker.ROOT_COLLECTION_NAME); public final static XmldbURI SYSTEM_COLLECTION_URI = create(DBBroker.SYSTEM_COLLECTION); public final static XmldbURI CONFIG_COLLECTION_URI = create(CollectionConfigurationManager.CONFIG_COLLECTION); public final static XmldbURI TEMP_COLLECTION_URI = create(DBBroker.TEMP_COLLECTION); public final static XmldbURI EMPTY_URI = createInternal(""); public static final XmldbURI EMBEDDED_SERVER_URI = XmldbURI.create(XMLDB_URI_PREFIX+DEFAULT_INSTANCE_NAME+"://"+EMBEDDED_SERVER_AUTHORITY); private String encodedCollectionPath; //TODO : deprecate when we split at root collection public final static String API_XMLRPC = "xmlrpc"; public final static String API_WEBDAV = "webdav"; public final static String API_REST = "rest-style"; public final static String API_LOCAL = "local"; public static XmldbURI xmldbUriFor(URI uri) throws URISyntaxException { return getXmldbURI(uri); } public static XmldbURI xmldbUriFor(String xmldbURI) throws URISyntaxException { if (xmldbURI==null) return null; URI uri = new URI(AnyURIValue.escape(xmldbURI)); return getXmldbURI(uri); } public static XmldbURI xmldbUriFor(String accessURI, String collectionPath) throws URISyntaxException { if (collectionPath==null) return null; URI uri = new URI(accessURI + URIUtils.iriToURI(collectionPath)); return getXmldbURI(uri); } public static XmldbURI create(URI uri){ try { return xmldbUriFor(uri); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid URI: "+e.getMessage()); } } public static XmldbURI create(String uri) { try { return xmldbUriFor(uri); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid URI: "+e.getMessage()); } } public static XmldbURI create(String accessURI, String collectionPath) { try { return xmldbUriFor(accessURI,collectionPath); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid URI: "+e.getMessage()); } } public static XmldbURI createInternal(String collectionPath) { return new XmldbURI(collectionPath); } private static XmldbURI getXmldbURI(URI uri) throws URISyntaxException{ if(uri.getScheme()!=null || uri.getFragment()!=null || uri.getQuery()!=null) { return new FullXmldbURI(uri); } return new XmldbURI(uri); /* //TODO : get rid of this and use a more robust approach (dedicated constructor ?) -pb //TODO : use named constants index = path.lastIndexOf("/xmlrpc"); if (index > lastIndex) { return false; } //TODO : use named constants index = path.lastIndexOf("/webdav"); if (index > lastIndex) { return false; } */ } /** * Contructs an XmldbURI from given URI. * The provided URI must have the XMLDB_SCHEME ("xmldb") * @param xmldbURI A string * @throws URISyntaxException If the given string is not a valid xmldb URI. */ protected XmldbURI(URI xmldbURI) throws URISyntaxException { boolean hadXmldbPrefix=false; if(xmldbURI.getScheme()!=null) { if (!XMLDB_SCHEME.equals(xmldbURI.getScheme())) { throw new URISyntaxException(xmldbURI.toString(), "xmldb URI scheme does not start with " + XMLDB_URI_PREFIX); } xmldbURI = new URI(xmldbURI.toString().substring(XMLDB_URI_PREFIX.length())); hadXmldbPrefix=true; } parseURI(xmldbURI,hadXmldbPrefix); } protected XmldbURI(String collectionPath) { this.encodedCollectionPath = collectionPath; } /** Feeds private members. Receives a URI with the xmldb: scheme already stripped * @throws URISyntaxException */ protected void parseURI(URI xmldbURI, boolean hadXmldbPrefix) throws URISyntaxException { splitPath(xmldbURI.getRawPath()); } /** Given a java.net.URI.getPath(), <strong>tries</strong> to dispatch the host's context * from the collection path as smartly as possible. * One would probably prefer a split policy based on the presence of a well-known root collection. * @param path The java.net.URI.getPath() provided. * @throws URISyntaxException */ protected void splitPath(String path) throws URISyntaxException { encodedCollectionPath = path; if (encodedCollectionPath != null && encodedCollectionPath.length() > 1 && encodedCollectionPath.endsWith("/")) encodedCollectionPath = encodedCollectionPath.substring(0, encodedCollectionPath.length() - 1); //TODO : check that collectionPath starts with DBBroker.ROOT_COLLECTION ? } protected void checkCompatibilityForContextOperation(XmldbURI uri) throws IllegalArgumentException { if (this.getInstanceName() != null && uri.getInstanceName() != null && !this.getInstanceName().equals(uri.getInstanceName())) throw new IllegalArgumentException(this.getInstanceName() + " instance differs from " + uri.getInstanceName()); //case insensitive comparison if (this.getHost() != null && uri.getHost() != null && !this.getHost().equalsIgnoreCase(uri.getHost())) throw new IllegalArgumentException(this.getHost() + " host differs from " + uri.getHost()); if (this.getPort() != NO_PORT && uri.getPort() != NO_PORT && this.getPort() != uri.getPort()) throw new IllegalArgumentException(this.getPort() + " port differs from " + uri.getPort()); if (this.getCollectionPath() != null && uri.getCollectionPath() != null && !this.getCollectionPath().equals(uri.getCollectionPath())) throw new IllegalArgumentException(this.getCollectionPath() + " collection differs from " + uri.getCollectionPath()); } protected void checkCompatibilityForCollectionOperation(XmldbURI uri) throws IllegalArgumentException { if (this.getInstanceName() != null && uri.getInstanceName() != null && !this.getInstanceName().equals(uri.getInstanceName())) throw new IllegalArgumentException(this.getInstanceName() + " instance differs from " + uri.getInstanceName()); //case insensitive comparison if (this.getHost() != null && uri.getHost() != null && !this.getHost().equalsIgnoreCase(uri.getHost())) throw new IllegalArgumentException(this.getHost() + " host differs from " + uri.getHost()); if (this.getPort() != NO_PORT && uri.getPort() != NO_PORT && this.getPort() != uri.getPort()) throw new IllegalArgumentException(this.getPort() + " port differs from " + uri.getPort()); if (this.getContext() != null && uri.getContext() != null && !this.getContext().equals(uri.getContext())) throw new IllegalArgumentException(this.getContext() + " context differs from " + uri.getContext()); } /* * It is an error for any of the following private members to throw an exception. */ /** * This returns a proper heirarchical URI - the xmldb scheme is trimmed * from the beginning. The scheme will be the instance name, and all * other fields will be populated as would be expected from a heirarchical * URI * * @see getXmldbURI */ public URI getURI() { return URI.create(encodedCollectionPath); } /** * This returns an xmldb uri. This is the most generic sort of uri - the * only fields set in the uri are scheme and schemeSpecificPart */ public URI getXmldbURI() { return URI.create(encodedCollectionPath); } public String getInstanceName() { return null; } /** * Method to return the collection path with reserved characters * percent encoded * * @return Returns the encoded collection path */ public String getRawCollectionPath() { return encodedCollectionPath; } public String getCollectionPath() { if (encodedCollectionPath == null) return null; try { //TODO: we might want to cache this value return URLDecoder.decode(encodedCollectionPath, "UTF-8"); } catch (UnsupportedEncodingException e) { //Should never happen throw new IllegalArgumentException(encodedCollectionPath + " can not be properly escaped"); } } public XmldbURI toCollectionPathURI() { return (this instanceof FullXmldbURI)?XmldbURI.create(getRawCollectionPath()):this; } /** To be called each time a private member that interacts with the wrapped URI is modified. * @throws URISyntaxException */ protected void recomputeURI() throws URISyntaxException { } /** To be called each time a private member that interacts with the wrapped URI is modified. * @throws URISyntaxException */ protected void safeRecomputeURI() { try { recomputeURI(); } catch(URISyntaxException e) {} } /* * Must be encoded! */ private void setCollectionPath(String collectionPath) { String oldCollectionPath = encodedCollectionPath; try { encodedCollectionPath = "".equals(collectionPath) ? null : collectionPath; //include root slash if we have a context if (encodedCollectionPath!=null && getContext() != null & encodedCollectionPath.charAt(0)!='/') { encodedCollectionPath = "/"+encodedCollectionPath; } recomputeURI(); } catch (URISyntaxException e) { encodedCollectionPath = oldCollectionPath; throw new IllegalArgumentException("Invalid URI: "+e.getMessage()); } } public String getApiName() { return null; } public String getContext() { return null; } public int compareTo(Object ob) throws ClassCastException { if (!(ob instanceof XmldbURI)) throw new ClassCastException("The provided Object is not an XmldbURI"); return getXmldbURI().compareTo((Object) ((XmldbURI)ob).getXmldbURI()); } /** * This function returns a relative XmldbURI with the value after the last * / in the collection path of the URI * * @return A relative XmldbURI containing the value after the last / * in the collection path */ public XmldbURI lastSegment() { String name = getRawCollectionPath(); int last; // No slash - give them the whole thing! if((last=name.lastIndexOf('/'))==Constants.STRING_NOT_FOUND) { return this; } // Checks against a trailing slash // is this appropriate? if(last==name.length()-1) { name = name.substring(0,last); last = name.lastIndexOf('/'); } return XmldbURI.create(name.substring(last+1)); } /** * This function returns a relative XmldbURI with the value after the last * / in the collection path of the URI * * @return A relative XmldbURI containing the value after the last / * in the collection path */ public int numSegments() { String name = getRawCollectionPath(); if(name==null || "".equals(name)) { return 0; } String[] split = name.split("/"); return split.length; } /** * This function returns a relative XmldbURI with the value after the last * / in the collection path of the URI * * @return A relative XmldbURI containing the value after the last / * in the collection path */ public XmldbURI[] getPathSegments() { String name = getRawCollectionPath(); if(name==null || "".equals(name)) { return new XmldbURI[0]; } String[] split = name.split("/"); int fix = ("".equals(split[0]))?1:0; XmldbURI[] segments = new XmldbURI[split.length-fix]; for(int i=fix;i<split.length;i++) { segments[i-fix] = XmldbURI.create(split[i]); } return segments; } /** * This function returns a string with everything after the last / removed * * @return A relative XmldbURI containing the value after the last / * in the collection path */ public XmldbURI removeLastSegment() { String uri = toString(); int last; // No slash - return null! if((last=uri.lastIndexOf('/'))==Constants.STRING_NOT_FOUND) { return XmldbURI.EMPTY_URI; } // Checks against a trailing slash // is this appropriate? if(last==uri.length()-1) { uri = uri.substring(0,last); last = uri.lastIndexOf('/'); } return last<=0?XmldbURI.EMPTY_URI:XmldbURI.create(uri.substring(0,last)); } public XmldbURI append(String uri) { return append(XmldbURI.create(uri)); } public XmldbURI append(XmldbURI uri) { String toAppend = uri.getRawCollectionPath(); String prepend = toString(); if("".equals(toAppend)) return this; if("".equals(prepend)) { return uri; } if(!(prepend.charAt(prepend.length()-1)=='/') && !(toAppend.charAt(0)=='/')) { return XmldbURI.create(prepend+"/"+toAppend); } else { return XmldbURI.create(prepend+toAppend); } } public XmldbURI appendInternal(XmldbURI uri) { return XmldbURI.createInternal(getRawCollectionPath() + '/' + uri.getRawCollectionPath()); } /** Ugly workaround for non-URI compliant pathes * @param pseudoURI What is supposed to be a URI * @return an supposedly correctly escaped URI <strong>string representation</string> * @deprecated By definition, using this method is strongly discouraged */ public static String recoverPseudoURIs(String pseudoURI) throws URISyntaxException { Pattern p = Pattern.compile("/"); String[] parts = p.split(pseudoURI); StringBuffer newURIString = new StringBuffer(parts[0]); for (int i = 1 ; i <parts.length; i ++) { newURIString.append("/"); if (!"".equals(parts[i])) { try { //Try to instantiate the parst as a URI new URI(newURIString + parts[i]); newURIString.append(parts[i]); } catch (URISyntaxException e) { LOG.info("Trying to escape : ''" + parts[i] + "' in '" + pseudoURI + "' !"); newURIString.append(URIUtils.encodeForURI(parts[i])); } } } return newURIString.toString(); } public boolean equals(Object ob) { if (ob instanceof XmldbURI) { return getXmldbURI().equals(((XmldbURI)ob).getXmldbURI()); } if (ob instanceof URI) { return getXmldbURI().equals(ob); } if (ob instanceof String) { try { return getXmldbURI().equals(new URI((String)ob)); } catch(URISyntaxException e) { return false; } } return false; } public boolean isAbsolute() { return isCollectionPathAbsolute(); } public boolean isContextAbsolute() { return false; } public XmldbURI normalizeContext() { return this; } public URI relativizeContext(URI uri) { return null; } public URI resolveContext(String str) throws NullPointerException, IllegalArgumentException { return null; } public URI resolveContext(URI uri) throws NullPointerException { return null; } public boolean isCollectionPathAbsolute() { return encodedCollectionPath!=null && encodedCollectionPath.charAt(0)=='/'; } public XmldbURI normalizeCollectionPath() { String collectionPath = this.encodedCollectionPath; if (collectionPath == null) return this; URI collectionPathURI = URI.create(collectionPath).normalize(); if(collectionPathURI.getPath().equals(collectionPath)) { return this; } XmldbURI uri = XmldbURI.create(getXmldbURI()); uri.setCollectionPath(collectionPathURI.toString()); return uri; } public URI relativizeCollectionPath(URI uri) { if (uri == null) throw new NullPointerException("The provided URI is null"); String collectionPath = this.encodedCollectionPath; if (collectionPath == null) throw new NullPointerException("The current collection path is null"); URI collectionPathURI; //Adds a final slash if necessary if (!collectionPath.endsWith("/")) { LOG.info("Added a final '/' to '" + collectionPath + "'"); collectionPathURI = URI.create(collectionPath + "/"); } else collectionPathURI = URI.create(collectionPath); return collectionPathURI.relativize(uri); } //TODO: unit test! public XmldbURI resolveCollectionPath(XmldbURI child) throws NullPointerException, IllegalArgumentException { if (child == null) throw new NullPointerException("The provided child URI is null"); //Old method: /* String collectionPath = this.encodedCollectionPath; if (collectionPath == null) throw new NullPointerException("The current collection path is null"); URI collectionPathURI; //Adds a final slash if necessary if (!collectionPath.endsWith("/")) { LOG.info("Added a final '/' to '" + collectionPath + "'"); collectionPathURI = URI.create(collectionPath + "/"); } else collectionPathURI = URI.create(collectionPath); */ String collectionPath = toCollectionPathURI().toString(); URI newCollectionURI = null; if(!collectionPath.endsWith("/")) { newCollectionURI = URI.create(collectionPath+"/").resolve(child.toCollectionPathURI().getURI()); } else { newCollectionURI = getURI().resolve(child.toCollectionPathURI().getURI()); } XmldbURI newURI = XmldbURI.create(getXmldbURI()); String newCollectionPath = newCollectionURI.getRawPath(); if(newCollectionPath.endsWith("/")) { newCollectionPath = newCollectionPath.substring(0,newCollectionPath.length()-1); } newURI.encodedCollectionPath=newCollectionPath; newURI.safeRecomputeURI(); return newURI; } public URI resolveCollectionPath(URI uri) throws NullPointerException { if (uri == null) throw new NullPointerException("The provided URI is null"); String collectionPath = this.encodedCollectionPath; if (collectionPath == null) throw new NullPointerException("The current collection path is null"); URI collectionPathURI; //Adds a final slash if necessary if (!collectionPath.endsWith("/")) { LOG.info("Added a final '/' to '" + collectionPath + "'"); collectionPathURI = URI.create(collectionPath + "/"); } else collectionPathURI = URI.create(collectionPath); return collectionPathURI.resolve(uri); } public String toASCIIString() { //TODO : trim trailing slash if necessary return getXmldbURI().toASCIIString(); } public URL toURL() throws IllegalArgumentException, MalformedURLException { return getXmldbURI().toURL(); } //TODO: add unit test for this public boolean startsWith(XmldbURI xmldbUri) { return (xmldbUri==null)? false : toString().startsWith(xmldbUri.toString()); } public boolean startsWith(String string) throws URISyntaxException { return startsWith(XmldbURI.xmldbUriFor(string)); } //TODO: add unit test for this public boolean endsWith(XmldbURI xmldbUri) { return (xmldbUri==null)? false : toString().endsWith(xmldbUri.toString()); } public boolean endsWith(String string) throws URISyntaxException { return endsWith(XmldbURI.xmldbUriFor(string)); } //TODO: add unit test for this public XmldbURI prepend(XmldbURI xmldbUri) { if(xmldbUri==null) { throw new NullPointerException(toString() + " cannot start with null!"); } return xmldbUri.append(this); } //TODO: add unit test for this public XmldbURI trimFromBeginning(XmldbURI xmldbUri) { if(xmldbUri==null) { throw new NullPointerException(toString() + " cannot start with null!"); } if(!startsWith(xmldbUri)) { throw new IllegalArgumentException(toString() + " does not start with " + xmldbUri.toString()); } return XmldbURI.create(toString().substring(xmldbUri.toString().length())); } public XmldbURI trimFromBeginning(String string) throws URISyntaxException { return trimFromBeginning(XmldbURI.xmldbUriFor(string)); } public String toString() { //TODO : trim trailing slash if necessary return getXmldbURI().toString(); } public static String[] getPathComponents(String collectionPath) { Pattern p = Pattern.compile("/"); String [] split = p.split(collectionPath); String [] result = new String[split.length - 1]; System.arraycopy(split, 1, result, 0, split.length - 1); return result; } /* @deprecated Legacy method used here and there in the code * if the currentPath is null return the parentPath else * if the currentPath doesnt not start with "/db/" and is not equal to "/db" then adjust the path to start with the parentPath * * Fix to Jens collection/resource name problem by deliriumsky * * @deprecated Use {@link #resolveCollectionPath(String) resolveCollectionPath} instead */ public static String checkPath(String currentPath, String parentPath) { if(currentPath == null) return parentPath; //Absolute path if (DBBroker.ROOT_COLLECTION.equals(currentPath)) return currentPath; //Absolute path if (currentPath.startsWith(DBBroker.ROOT_COLLECTION + "/")) return currentPath; //Kind of relative path : against all conventions ! -pb if(currentPath.startsWith("/")) LOG.warn("Initial '/' for relative path '" + currentPath + "'"); //OK : let's process this so-called relative path if (currentPath.startsWith("/")) { if (parentPath.endsWith("/")) return parentPath + currentPath.substring(1); return parentPath + currentPath; } //True relative pathes if (parentPath.endsWith("/")) return parentPath + currentPath; return parentPath + "/" + currentPath; } /** @deprecated Legacy method used here and there in the code * @param fileName * @param parentPath * @return */ public static String checkPath2(String fileName, String parentPath) { //if (!fileName.startsWith("/")) // fileName = "/" + fileName; /*if (!fileName.startsWith(ROOT_COLLECTION)) fileName = ROOT_COLLECTION + fileName;*/ return checkPath(fileName, parentPath); } /**@deprecated Legacy method used here and there in the code and copied as such * @param name * @return */ //TODO : changes // into / */ public String makeAbsolute(String name) { StringBuffer out = new StringBuffer(); for (int i = 0; i < name.length(); i++) //TODO : use dedicated function in XmldbURI if (name.charAt(i) == '/' && name.length() > i + 1 && name.charAt(i + 1) == '/') i++; else out.append(name.charAt(i)); String name2 = out.toString(); if (name2.length() > 0 && name2.charAt(0) != '/') name2 = "/" + name2; if (!name2.startsWith(DBBroker.ROOT_COLLECTION)) name2 = DBBroker.ROOT_COLLECTION + name2; if (name2.endsWith("/") && name2.length() > 1) name2 = name2.substring(0, name2.length() - 1); return name2; } /**@deprecated Legacy method used here and there in the code and copied as such * @param name * @return */ //TODO : changes // into / */ public final static String normalizeCollectionName(String name) { StringBuffer out = new StringBuffer(); for (int i = 0; i < name.length(); i++) //TODO : use dedicated function in XmldbURI if (name.charAt(i) == '/' && name.length() > i + 1 && name.charAt(i + 1) == '/') i++; else out.append(name.charAt(i)); String name2 = out.toString(); if (name2.length() > 0 && name2.charAt(0) != '/') name2 = "/" + name2; if (!name2.startsWith(DBBroker.ROOT_COLLECTION)) name2 = DBBroker.ROOT_COLLECTION + name2; if (name2.endsWith("/") && name2.length() > 1) name2 = name2.substring(0, name2.length() - 1); return name2; } /* (non-Javadoc) * @see java.net.URI#getAuthority() */ public String getAuthority() { return null; } /* (non-Javadoc) * @see java.net.URI#getFragment() */ public String getFragment() { return null; } /* (non-Javadoc) * @see java.net.URI#getPort() */ public int getPort() { return NO_PORT; } /* (non-Javadoc) * @see java.net.URI#getQuery() */ public String getQuery() { return null; } /* (non-Javadoc) * @see java.net.URI#getRawAuthority() */ public String getRawAuthority() { return null; } /* (non-Javadoc) * @see java.net.URI#getHost() */ public String getHost() { return null; } /* (non-Javadoc) * @see java.net.URI#getUserInfo() */ public String getUserInfo() { return null; } /* (non-Javadoc) * @see java.net.URI#getRawFragment() */ public String getRawFragment() { return null; } /* (non-Javadoc) * @see java.net.URI#getRawQuery() */ public String getRawQuery() { return null; } /* (non-Javadoc) * @see java.net.URI#getRawUserInfo() */ public String getRawUserInfo() { return null; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return getXmldbURI().hashCode(); } // TODO : prefefined URIs as static classes... }
package org.inceptus.drive; import edu.wpi.first.wpilibj.CANJaguar; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.RobotDrive.MotorType; import edu.wpi.first.wpilibj.can.CANTimeoutException; import org.inceptus.debug.Debug; /** * * @author innoying */ public class Drive { //Motors private CANJaguar leftFront; private CANJaguar rightFront; private CANJaguar leftRear; private CANJaguar rightRear; //Drive private RobotDrive robotDrive; //Initilize public boolean Init(){ //Try catch for errors try { //Setup the drive motors leftFront = new CANJaguar(12); rightFront = new CANJaguar(11); leftRear = new CANJaguar(10); rightRear = new CANJaguar(5); //Setup the Drive robotDrive = new RobotDrive(leftFront, leftRear, rightFront, rightRear); //Invert the motors robotDrive.setInvertedMotor(MotorType.kFrontLeft, true); robotDrive.setInvertedMotor(MotorType.kRearRight, false); robotDrive.setInvertedMotor(MotorType.kFrontLeft, true); robotDrive.setInvertedMotor(MotorType.kRearLeft, true); } catch (CANTimeoutException ex) { //Catch CANTimeout Error //Print Error Debug.fatal(ex, "CAN Timeout in Drive"); //Return failure return false; } catch (Exception ex){ //Catch all for errors //Print Error Debug.fatal(ex, "Unknown error in Drive"); //Return failure return false; } //Return Success return true; } public boolean DriveWithValues(double x, double y, double rotation, double throttle){ //Try catch for errors try { //Setup min and max values for magnitude final double magnitudeMin = .3; final double magnitudeMax = .7; //Setup the twist multiplier final double twistMultiplier = .5; //Adjust throttle to 0-1 range throttle = ( ( throttle + 1 ) / 2 ); //Scale the magnitude down to not overpower the motors throttle = magnitudeMin + ( throttle * (magnitudeMax - magnitudeMin) ); //Scale the throttle with each of the values x = x * (1 - throttle); y = y * (1 - throttle); //Scale the rotation with the value rotation = rotation * twistMultiplier; //Drive using values robotDrive.mecanumDrive_Cartesian(x, y, rotation, 0); } catch (Exception ex){ //Catch all for errors //Print Error Debug.fatal(ex, "Unknown error in DriveWithValues"); //Return failure return false; } //Return Success return true; } }
package com.sbugert.rnadmob; import android.os.Handler; import android.os.Looper; import android.support.annotation.Nullable; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableNativeArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableArray; import com.facebook.react.modules.core.DeviceEventManagerModule; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.InterstitialAd; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class RNAdMobInterstitialAdModule extends ReactContextBaseJavaModule { public static final String REACT_CLASS = "RNAdMobInterstitial"; public static final String EVENT_AD_LOADED = "interstitialAdLoaded"; public static final String EVENT_AD_FAILED_TO_LOAD = "interstitialAdFailedToLoad"; public static final String EVENT_AD_OPENED = "interstitialAdOpened"; public static final String EVENT_AD_CLOSED = "interstitialAdClosed"; public static final String EVENT_AD_LEFT_APPLICATION = "interstitialAdLeftApplication"; InterstitialAd mInterstitialAd; String[] testDevices; private Promise mRequestAdPromise; @Override public String getName() { return REACT_CLASS; } public RNAdMobInterstitialAdModule(ReactApplicationContext reactContext) { super(reactContext); mInterstitialAd = new InterstitialAd(reactContext); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { mInterstitialAd.setAdListener(new AdListener() { @Override public void onAdClosed() { sendEvent(EVENT_AD_CLOSED, null); } @Override public void onAdFailedToLoad(int errorCode) { String errorString = "ERROR_UNKNOWN"; String errorMessage = "Unknown error"; switch (errorCode) { case AdRequest.ERROR_CODE_INTERNAL_ERROR: errorString = "ERROR_CODE_INTERNAL_ERROR"; errorMessage = "Internal error, an invalid response was received from the ad server."; break; case AdRequest.ERROR_CODE_INVALID_REQUEST: errorString = "ERROR_CODE_INVALID_REQUEST"; errorMessage = "Invalid ad request, possibly an incorrect ad unit ID was given."; break; case AdRequest.ERROR_CODE_NETWORK_ERROR: errorString = "ERROR_CODE_NETWORK_ERROR"; errorMessage = "The ad request was unsuccessful due to network connectivity."; break; case AdRequest.ERROR_CODE_NO_FILL: errorString = "ERROR_CODE_NO_FILL"; errorMessage = "The ad request was successful, but no ad was returned due to lack of ad inventory."; break; } WritableMap event = Arguments.createMap(); WritableMap error = Arguments.createMap(); event.putString("message", errorMessage); sendEvent(EVENT_AD_FAILED_TO_LOAD, event); mRequestAdPromise.reject(errorString, errorMessage); } @Override public void onAdLeftApplication() { sendEvent(EVENT_AD_LEFT_APPLICATION, null); } @Override public void onAdLoaded() { sendEvent(EVENT_AD_LOADED, null); mRequestAdPromise.resolve(null); } @Override public void onAdOpened() { sendEvent(EVENT_AD_OPENED, null); } }); } }); } private void sendEvent(String eventName, @Nullable WritableMap params) { getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, params); } @ReactMethod public void setAdUnitID(String adUnitID) { if (mInterstitialAd.getAdUnitId() == null) { mInterstitialAd.setAdUnitId(adUnitID); } } @ReactMethod public void setTestDevices(ReadableArray testDevices) { ReadableNativeArray nativeArray = (ReadableNativeArray)testDevices; ArrayList<Object> list = nativeArray.toArrayList(); this.testDevices = list.toArray(new String[list.size()]); } @ReactMethod public void requestAd(final Promise promise) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run () { if (mInterstitialAd.isLoaded() || mInterstitialAd.isLoading()) { promise.reject("E_AD_ALREADY_LOADED", "Ad is already loaded."); } else { mRequestAdPromise = promise; AdRequest.Builder adRequestBuilder = new AdRequest.Builder(); if (testDevices != null) { for (int i = 0; i < testDevices.length; i++) { adRequestBuilder.addTestDevice(testDevices[i]); } } AdRequest adRequest = adRequestBuilder.build(); mInterstitialAd.loadAd(adRequest); } } }); } @ReactMethod public void showAd(final Promise promise) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run () { if (mInterstitialAd.isLoaded()) { mInterstitialAd.show(); promise.resolve(null); } else { promise.reject("E_AD_NOT_READY", "Ad is not ready."); } } }); } @ReactMethod public void isReady(final Callback callback) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run () { callback.invoke(mInterstitialAd.isLoaded()); } }); } @javax.annotation.Nullable @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); constants.put("simulatorId", AdRequest.DEVICE_ID_EMULATOR); return constants; } }
package org.appcelerator.titanium.view; import org.appcelerator.kroll.common.TiMessenger; import org.appcelerator.titanium.proxy.TiViewProxy; import android.app.Activity; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.MotionEvent; public abstract class TiUIFragment extends TiUIView implements Handler.Callback { private static int viewId = 1000; private Fragment fragment; private Handler handler; public TiUIFragment(TiViewProxy proxy, Activity activity) { super(proxy); TiCompositeLayout container = new TiCompositeLayout(activity, proxy) { @Override public boolean dispatchTouchEvent(MotionEvent ev) { return interceptTouchEvent(ev) || super.dispatchTouchEvent(ev); } }; container.setId(viewId++); setNativeView(container); FragmentManager manager = ((FragmentActivity) activity).getSupportFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); fragment = createFragment(); transaction.add(container.getId(), fragment); transaction.commit(); // initialize handler handler = new Handler(TiMessenger.getMainMessenger().getLooper(), this); // send a msg to skip a cycle to make sure the fragment's view is created and initialized handler.obtainMessage().sendToTarget(); } public Fragment getFragment() { return fragment; } public boolean handleMessage(Message msg) { // we know here that the view is available, so we can process properties onViewCreated(); return true; } protected boolean interceptTouchEvent(MotionEvent ev) { return false; } protected abstract void onViewCreated(); protected abstract Fragment createFragment(); }
package org.jgroups.protocols; import org.jgroups.*; import org.jgroups.annotations.GuardedBy; import org.jgroups.stack.Protocol; import org.jgroups.util.*; import java.io.*; import java.util.*; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Failure detection based on simple heartbeat protocol. Regularly polls members for * liveness. Multicasts SUSPECT messages when a member is not reachable. The simple * algorithms works as follows: the membership is known and ordered. Each HB protocol * periodically sends an 'are-you-alive' message to its *neighbor*. A neighbor is the next in * rank in the membership list, which is recomputed upon a view change. When a response hasn't * been received for n milliseconds and m tries, the corresponding member is suspected (and * eventually excluded if faulty).<p> * FD starts when it detects (in a view change notification) that there are at least * 2 members in the group. It stops running when the membership drops below 2.<p> * When a message is received from the monitored neighbor member, it causes the pinger thread to * 'skip' sending the next are-you-alive message. Thus, traffic is reduced.<p> * When we receive a ping from a member that's not in the membership list, we shun it by sending it a * NOT_MEMBER message. That member will then leave the group (and possibly rejoin). This is only done if * <code>shun</code> is true. * @author Bela Ban * @version $Id: FD.java,v 1.57 2007/07/10 14:19:04 belaban Exp $ */ public class FD extends Protocol { Address ping_dest=null; Address local_addr=null; long timeout=3000; // number of millisecs to wait for an are-you-alive msg long last_ack=System.currentTimeMillis(); int num_tries=0; int max_tries=2; // number of times to send a are-you-alive msg (tot time= max_tries*timeout) final List<Address> members=new CopyOnWriteArrayList<Address>(); final Hashtable<Address,Integer> invalid_pingers=new Hashtable<Address,Integer>(7); // keys=Address, val=Integer (number of pings from suspected mbrs) /** Members from which we select ping_dest. may be subset of {@link #members} */ final List<Address> pingable_mbrs=new CopyOnWriteArrayList<Address>(); boolean shun=true; TimeScheduler timer=null; @GuardedBy("monitor_lock") private Future monitor_future=null; // task that performs the actual monitoring for failure detection private final Lock monitor_lock=new ReentrantLock(); protected int num_heartbeats=0; protected int num_suspect_events=0; /** Transmits SUSPECT message until view change or UNSUSPECT is received */ protected final Broadcaster bcast_task=new Broadcaster(); final static String name="FD"; BoundedList suspect_history=new BoundedList(20); public String getName() {return name;} public String getLocalAddress() {return local_addr != null? local_addr.toString() : "null";} public String getMembers() {return members != null? members.toString() : "null";} public String getPingableMembers() {return pingable_mbrs != null? pingable_mbrs.toString() : "null";} public String getPingDest() {return ping_dest != null? ping_dest.toString() : "null";} public int getNumberOfHeartbeatsSent() {return num_heartbeats;} public int getNumSuspectEventsGenerated() {return num_suspect_events;} public long getTimeout() {return timeout;} public void setTimeout(long timeout) {this.timeout=timeout;} public int getMaxTries() {return max_tries;} public void setMaxTries(int max_tries) {this.max_tries=max_tries;} public int getCurrentNumTries() {return num_tries;} public boolean isShun() {return shun;} public void setShun(boolean flag) {this.shun=flag;} public String printSuspectHistory() { StringBuilder sb=new StringBuilder(); for(Enumeration en=suspect_history.elements(); en.hasMoreElements();) { sb.append(new Date()).append(": ").append(en.nextElement()).append("\n"); } return sb.toString(); } public boolean setProperties(Properties props) { String str; super.setProperties(props); str=props.getProperty("timeout"); if(str != null) { timeout=Long.parseLong(str); props.remove("timeout"); } str=props.getProperty("max_tries"); // before suspecting a member if(str != null) { max_tries=Integer.parseInt(str); props.remove("max_tries"); } str=props.getProperty("shun"); if(str != null) { shun=Boolean.valueOf(str).booleanValue(); props.remove("shun"); } if(!props.isEmpty()) { log.error("the following properties are not recognized: " + props); return false; } return true; } public void resetStats() { num_heartbeats=num_suspect_events=0; suspect_history.removeAll(); } public void init() throws Exception { if(stack != null && stack.timer != null) timer=stack.timer; else throw new Exception("FD.init(): timer cannot be retrieved from protocol stack"); } public void stop() { stopMonitor(); } private Object getPingDest(List mbrs) { Object tmp, retval=null; if(mbrs == null || mbrs.size() < 2 || local_addr == null) return null; for(int i=0; i < mbrs.size(); i++) { tmp=mbrs.get(i); if(local_addr.equals(tmp)) { if(i + 1 >= mbrs.size()) retval=mbrs.get(0); else retval=mbrs.get(i + 1); break; } } return retval; } private void startMonitor() { monitor_lock.lock(); try { if(monitor_future == null || monitor_future.isDone()) { last_ack=System.currentTimeMillis(); // start from scratch monitor_future=timer.scheduleWithFixedDelay(new Monitor(), timeout, timeout, TimeUnit.MILLISECONDS); num_tries=0; } } finally { monitor_lock.unlock(); } } private void stopMonitor() { monitor_lock.lock(); try { if(monitor_future != null) { monitor_future.cancel(true); monitor_future=null; } } finally { monitor_lock.unlock(); } } public Object up(Event evt) { switch(evt.getType()) { case Event.SET_LOCAL_ADDRESS: local_addr=(Address)evt.getArg(); break; case Event.MSG: Message msg=(Message)evt.getArg(); FdHeader hdr=(FdHeader)msg.getHeader(name); if(hdr == null) { Object sender; if(ping_dest != null && (sender=msg.getSrc()) != null) { if(ping_dest.equals(sender)) { last_ack=System.currentTimeMillis(); if(log.isTraceEnabled()) log.trace("received msg from " + sender + " (counts as ack)"); num_tries=0; } } break; // message did not originate from FD layer, just pass up } switch(hdr.type) { case FdHeader.HEARTBEAT: // heartbeat request; send heartbeat ack Address hb_sender=msg.getSrc(); if(log.isTraceEnabled()) log.trace("received are-you-alive from " + hb_sender + ", sending response"); sendHeartbeatResponse(hb_sender); // 2. Shun the sender of a HEARTBEAT message if that sender is not a member. This will cause // the sender to leave the group (and possibly rejoin it later) if(shun) shunInvalidHeartbeatSender(hb_sender); break; // don't pass up ! case FdHeader.HEARTBEAT_ACK: // heartbeat ack // if(ping_dest != null && ping_dest.equals(hdr.from)) { // last_ack=System.currentTimeMillis(); // num_tries=0; // if(log.isDebugEnabled()) log.debug("received ack from " + hdr.from); // else { // stop(); // ping_dest=(Address)getPingDest(pingable_mbrs); // if(ping_dest != null) { // try { // startMonitor(); // catch(Exception ex) { // if(log.isWarnEnabled()) log.warn("exception when calling startMonitor(): " + ex); if(ping_dest != null && ping_dest.equals(hdr.from)) { last_ack=System.currentTimeMillis(); num_tries=0; if(log.isDebugEnabled()) log.debug("received ack from " + hdr.from); } else { synchronized(this) { Address previewNextPingDest = (Address)getPingDest(pingable_mbrs); /* We are only interested to stop or restart the monitor thread iff the current target ping_dest is going change */ if(log.isDebugEnabled()) log.debug("Recevied Ack. is invalid (was from: " + hdr.from + "), "); if ((previewNextPingDest != null && ping_dest != null && !previewNextPingDest.equals(ping_dest)) || (previewNextPingDest != null && ping_dest == null) || (previewNextPingDest == null && ping_dest != null)) { stop(); ping_dest= previewNextPingDest; if(log.isDebugEnabled()) log.debug("changing to a new destination: " + ping_dest); if(ping_dest != null) { try { startMonitor(); } catch(Exception ex) { if(log.isWarnEnabled()) log.warn("exception when calling startMonitor(): " + ex); } } } else if (ping_dest == null) { if(log.isTraceEnabled()) log.trace("and ping_dest is null, stop Monitor"); stop(); } else { if(log.isTraceEnabled()) log.trace("but we must keep pinging same destination"); } } } break; case FdHeader.SUSPECT: if(hdr.mbrs != null) { if(log.isTraceEnabled()) log.trace("[SUSPECT] suspect hdr is " + hdr); for(int i=0; i < hdr.mbrs.size(); i++) { Address m=hdr.mbrs.elementAt(i); if(local_addr != null && m.equals(local_addr)) { if(log.isWarnEnabled()) log.warn("I was suspected by " + msg.getSrc() + "; ignoring the SUSPECT " + "message and sending back a HEARTBEAT_ACK"); sendHeartbeatResponse(msg.getSrc()); continue; } else { pingable_mbrs.remove(m); ping_dest=(Address)getPingDest(pingable_mbrs); } up_prot.up(new Event(Event.SUSPECT, m)); down_prot.down(new Event(Event.SUSPECT, m)); } } break; case FdHeader.NOT_MEMBER: if(shun) { if(log.isDebugEnabled()) log.debug("[NOT_MEMBER] I'm being shunned; exiting"); up_prot.up(new Event(Event.EXIT)); } break; } return null; } return up_prot.up(evt); // pass up to the layer above us } public Object down(Event evt) { switch(evt.getType()) { case Event.VIEW_CHANGE: down_prot.down(evt); stop(); synchronized(this) { View v=(View)evt.getArg(); members.clear(); members.addAll(v.getMembers()); bcast_task.adjustSuspectedMembers(members); pingable_mbrs.clear(); pingable_mbrs.addAll(members); ping_dest=(Address)getPingDest(pingable_mbrs); if(ping_dest != null) { try { startMonitor(); } catch(Exception ex) { if(log.isWarnEnabled()) log.warn("exception when calling startMonitor(): " + ex); } } } return null; case Event.UNSUSPECT: unsuspect((Address)evt.getArg()); return down_prot.down(evt); } return down_prot.down(evt); } private void sendHeartbeatResponse(Address dest) { Message hb_ack=new Message(dest, null, null); hb_ack.setFlag(Message.OOB); FdHeader tmp_hdr=new FdHeader(FdHeader.HEARTBEAT_ACK); tmp_hdr.from=local_addr; hb_ack.putHeader(name, tmp_hdr); down_prot.down(new Event(Event.MSG, hb_ack)); } private void unsuspect(Address mbr) { bcast_task.removeSuspectedMember(mbr); pingable_mbrs.clear(); pingable_mbrs.addAll(members); pingable_mbrs.removeAll(bcast_task.getSuspectedMembers()); ping_dest=(Address)getPingDest(pingable_mbrs); if(ping_dest != null) { try { startMonitor(); } catch(Exception ex) { if(log.isWarnEnabled()) log.warn("exception when calling unsuspect(): " + ex); } } } /** * If sender is not a member, send a NOT_MEMBER to sender (after n pings received) */ private void shunInvalidHeartbeatSender(Address hb_sender) { int num_pings=0; Message shun_msg; if(hb_sender != null && members != null && !members.contains(hb_sender)) { if(invalid_pingers.containsKey(hb_sender)) { num_pings=invalid_pingers.get(hb_sender).intValue(); if(num_pings >= max_tries) { if(log.isDebugEnabled()) log.debug(hb_sender + " is not in " + members + " ! Shunning it"); shun_msg=new Message(hb_sender, null, null); shun_msg.setFlag(Message.OOB); shun_msg.putHeader(name, new FdHeader(FdHeader.NOT_MEMBER)); down_prot.down(new Event(Event.MSG, shun_msg)); invalid_pingers.remove(hb_sender); } else { num_pings++; invalid_pingers.put(hb_sender, new Integer(num_pings)); } } else { num_pings++; invalid_pingers.put(hb_sender, new Integer(num_pings)); } } } public static class FdHeader extends Header implements Streamable { public static final byte HEARTBEAT=0; public static final byte HEARTBEAT_ACK=1; public static final byte SUSPECT=2; public static final byte NOT_MEMBER=3; // received as response by pinged mbr when we are not a member byte type=HEARTBEAT; Vector<Address> mbrs=null; Address from=null; // member who detected that suspected_mbr has failed public FdHeader() { } // used for externalization public FdHeader(byte type) { this.type=type; } public FdHeader(byte type, Vector<Address> mbrs, Address from) { this(type); this.mbrs=mbrs; this.from=from; } public String toString() { switch(type) { case HEARTBEAT: return "heartbeat"; case HEARTBEAT_ACK: return "heartbeat ack"; case SUSPECT: return "SUSPECT (suspected_mbrs=" + mbrs + ", from=" + from + ")"; case NOT_MEMBER: return "NOT_MEMBER"; default: return "unknown type (" + type + ")"; } } public void writeExternal(ObjectOutput out) throws IOException { out.writeByte(type); if(mbrs == null) out.writeBoolean(false); else { out.writeBoolean(true); out.writeInt(mbrs.size()); for(Iterator it=mbrs.iterator(); it.hasNext();) { Address addr=(Address)it.next(); Marshaller.write(addr, out); } } Marshaller.write(from, out); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { type=in.readByte(); boolean mbrs_not_null=in.readBoolean(); if(mbrs_not_null) { int len=in.readInt(); mbrs=new Vector<Address>(11); for(int i=0; i < len; i++) { Address addr=(Address)Marshaller.read(in); mbrs.add(addr); } } from=(Address)Marshaller.read(in); } public int size() { int retval=Global.BYTE_SIZE; // type retval+=Util.size(mbrs); retval+=Util.size(from); return retval; } public void writeTo(DataOutputStream out) throws IOException { out.writeByte(type); Util.writeAddresses(mbrs, out); Util.writeAddress(from, out); } public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { type=in.readByte(); mbrs=(Vector<Address>)Util.readAddresses(in, Vector.class); from=Util.readAddress(in); } } protected class Monitor implements Runnable { public void run() { Message hb_req; long not_heard_from; // time in msecs we haven't heard from ping_dest if(ping_dest == null) { if(log.isWarnEnabled()) log.warn("ping_dest is null: members=" + members + ", pingable_mbrs=" + pingable_mbrs + ", local_addr=" + local_addr); return; } // 1. send heartbeat request hb_req=new Message(ping_dest, null, null); hb_req.setFlag(Message.OOB); hb_req.putHeader(name, new FdHeader(FdHeader.HEARTBEAT)); // send heartbeat request if(log.isDebugEnabled()) log.debug("sending are-you-alive msg to " + ping_dest + " (own address=" + local_addr + ')'); down_prot.down(new Event(Event.MSG, hb_req)); num_heartbeats++; // 2. If the time of the last heartbeat is > timeout and max_tries heartbeat messages have not been // received, then broadcast a SUSPECT message. Will be handled by coordinator, which may install // a new view not_heard_from=System.currentTimeMillis() - last_ack; // quick & dirty fix: increase timeout by 500msecs to allow for latency (bela June 27 2003) if(not_heard_from > timeout + 500) { // no heartbeat ack for more than timeout msecs if(num_tries >= max_tries) { if(log.isDebugEnabled()) log.debug("[" + local_addr + "]: received no heartbeat ack from " + ping_dest + " for " + (num_tries +1) + " times (" + ((num_tries+1) * timeout) + " milliseconds), suspecting it"); // broadcast a SUSPECT message to all members - loop until // unsuspect or view change is received bcast_task.addSuspectedMember(ping_dest); num_tries=0; if(stats) { num_suspect_events++; suspect_history.add(ping_dest); } } else { if(log.isDebugEnabled()) log.debug("heartbeat missing from " + ping_dest + " (number=" + num_tries + ')'); num_tries++; } } } } /** * Task that periodically broadcasts a list of suspected members to the group. Goal is not to lose * a SUSPECT message: since these are bcast unreliably, they might get dropped. The BroadcastTask makes * sure they are retransmitted until a view has been received which doesn't contain the suspected members * any longer. Then the task terminates. */ protected final class Broadcaster { final Vector<Address> suspected_mbrs=new Vector<Address>(7); final Lock bcast_lock=new ReentrantLock(); @GuardedBy("bcast_lock") Future bcast_future=null; @GuardedBy("bcast_lock") BroadcastTask task; Vector getSuspectedMembers() { return suspected_mbrs; } /** * Starts a new task, or - if already running - adds the argument to the running task. * @param suspect */ private void startBroadcastTask(Address suspect) { bcast_lock.lock(); try { if(bcast_future == null || bcast_future.isDone()) { task=new BroadcastTask((Vector<Address>)suspected_mbrs.clone()); task.addSuspectedMember(suspect); bcast_future=timer.scheduleWithFixedDelay(task, 0, // run immediately the first time timeout, // then every timeout milliseconds, until cancelled TimeUnit.MILLISECONDS); if(log.isTraceEnabled()) log.trace("BroadcastTask started"); } else { task.addSuspectedMember(suspect); } } finally { bcast_lock.unlock(); } } private void stopBroadcastTask() { bcast_lock.lock(); try { if(bcast_future != null) { bcast_future.cancel(true); bcast_future=null; task=null; } } finally { bcast_lock.unlock(); } } /** Adds a suspected member. Starts the task if not yet running */ protected void addSuspectedMember(Address mbr) { if(mbr == null) return; if(!members.contains(mbr)) return; synchronized(suspected_mbrs) { if(!suspected_mbrs.contains(mbr)) { suspected_mbrs.addElement(mbr); startBroadcastTask(mbr); } } } void removeSuspectedMember(Address suspected_mbr) { if(suspected_mbr == null) return; if(log.isDebugEnabled()) log.debug("member is " + suspected_mbr); synchronized(suspected_mbrs) { suspected_mbrs.removeElement(suspected_mbr); if(suspected_mbrs.isEmpty()) stopBroadcastTask(); } } /** Removes all elements from suspected_mbrs that are <em>not</em> in the new membership */ void adjustSuspectedMembers(List new_mbrship) { if(new_mbrship == null || new_mbrship.isEmpty()) return; StringBuilder sb=new StringBuilder(); synchronized(suspected_mbrs) { sb.append("suspected_mbrs: ").append(suspected_mbrs); suspected_mbrs.retainAll(new_mbrship); if(suspected_mbrs.isEmpty()) stopBroadcastTask(); sb.append(", after adjustment: ").append(suspected_mbrs); log.debug(sb.toString()); } } } protected final class BroadcastTask implements Runnable { private final Vector<Address> suspected_members=new Vector<Address>(); BroadcastTask(Vector<Address> suspected_members) { this.suspected_members.addAll(suspected_members); } public void stop() { suspected_members.clear(); if(log.isTraceEnabled()) log.trace("BroadcastTask stopped"); } public void run() { Message suspect_msg; FD.FdHeader hdr; synchronized(suspected_members) { if(suspected_members.isEmpty()) { stop(); if(log.isDebugEnabled()) log.debug("task done (no suspected members)"); return; } hdr=new FdHeader(FdHeader.SUSPECT); hdr.mbrs=(Vector<Address>)suspected_members.clone(); hdr.from=local_addr; } suspect_msg=new Message(); // mcast SUSPECT to all members suspect_msg.setFlag(Message.OOB); suspect_msg.putHeader(name, hdr); if(log.isDebugEnabled()) log.debug("broadcasting SUSPECT message [suspected_mbrs=" + suspected_members + "] to group"); down_prot.down(new Event(Event.MSG, suspect_msg)); if(log.isDebugEnabled()) log.debug("task done"); } public void addSuspectedMember(Address suspect) { if(suspect != null && !suspected_members.contains(suspect)) { suspected_members.add(suspect); } } } }
package org.jgroups.protocols; import org.jgroups.*; import org.jgroups.annotations.GuardedBy; import org.jgroups.annotations.MBean; import org.jgroups.annotations.ManagedAttribute; import org.jgroups.annotations.ManagedOperation; import org.jgroups.annotations.Property; import org.jgroups.stack.Protocol; import org.jgroups.util.*; import java.io.*; import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Failure detection based on simple heartbeat protocol. Regularly polls members * for liveness. Multicasts SUSPECT messages when a member is not reachable. The * simple algorithms works as follows: the membership is known and ordered. Each * HB protocol periodically sends an 'are-you-alive' message to its *neighbor*. * A neighbor is the next in rank in the membership list, which is recomputed * upon a view change. When a response hasn't been received for n milliseconds * and m tries, the corresponding member is suspected (and eventually excluded * if faulty). * <p> * FD starts when it detects (in a view change notification) that there are at * least 2 members in the group. It stops running when the membership drops * below 2. * <p> * When a message is received from the monitored neighbor member, it causes the * pinger thread to 'skip' sending the next are-you-alive message. Thus, traffic * is reduced. * <p> * When we receive a ping from a member that's not in the membership list, we * shun it by sending it a NOT_MEMBER message. That member will then leave the * group (and possibly rejoin). This is only done if <code>shun</code> is * true. * * @author Bela Ban * @version $Id: FD.java,v 1.71 2008/07/16 15:36:07 vlada Exp $ */ @MBean(description="Failure detection based on simple heartbeat protocol") public class FD extends Protocol { private final static String name="FD"; @Property(description="Timeout to suspect a node P if neither a heartbeat nor data were received from P. Default is 3000 msec") @ManagedAttribute(description="Timeout in msec to suspect a node P if neither a heartbeat nor data were received from P", writable=true) long timeout=3000; @Property(description="Shun switch") @ManagedAttribute(description="Shun switch", writable=true) boolean shun=true; @Property(description="Number of times to send heartbeat") @ManagedAttribute(description="Number of times to send a are-you-alive msg", writable=true) int max_tries=2; protected int num_heartbeats=0; protected int num_suspect_events=0; private final BoundedList<Address> suspect_history=new BoundedList<Address>(20); private Address local_addr=null; private long last_ack=System.currentTimeMillis(); private int num_tries=0; protected final Lock lock=new ReentrantLock(); @GuardedBy("lock") private Address ping_dest=null; @GuardedBy("lock") private final List<Address> members=new ArrayList<Address>(); /** Members from which we select ping_dest. may be subset of {@link #members} */ @GuardedBy("lock") private final List<Address> pingable_mbrs=new ArrayList<Address>(); @GuardedBy("lock") private final Map<Address,Integer> invalid_pingers=new HashMap<Address,Integer>(7); private TimeScheduler timer=null; @GuardedBy("lock") private Future<?> monitor_future=null; // task that performs the actual monitoring for failure detection /** Transmits SUSPECT message until view change or UNSUSPECT is received */ protected final Broadcaster bcast_task=new Broadcaster(); public String getName() {return name;} @ManagedAttribute(description="Member address") public String getLocalAddress() {return local_addr != null? local_addr.toString() : "null";} @ManagedAttribute(description="List of cluster members") public String getMembers() {return members != null? members.toString() : "null";} @ManagedAttribute(description="List of pingable members of a cluster") public String getPingableMembers() {return pingable_mbrs != null? pingable_mbrs.toString() : "null";} @ManagedAttribute(description="Ping destination") public String getPingDest() {return ping_dest != null? ping_dest.toString() : "null";} @ManagedAttribute(description="Number of heartbeats sent") public int getNumberOfHeartbeatsSent() {return num_heartbeats;} @ManagedAttribute(description="Number of suspect events received") public int getNumSuspectEventsGenerated() {return num_suspect_events;} public long getTimeout() {return timeout;} public void setTimeout(long timeout) {this.timeout=timeout;} public int getMaxTries() {return max_tries;} public void setMaxTries(int max_tries) {this.max_tries=max_tries;} public int getCurrentNumTries() {return num_tries;} public boolean isShun() {return shun;} public void setShun(boolean flag) {this.shun=flag;} @ManagedOperation(description="Print suspect history") public String printSuspectHistory() { StringBuilder sb=new StringBuilder(); for(Address addr: suspect_history) { sb.append(new Date()).append(": ").append(addr).append("\n"); } return sb.toString(); } public void resetStats() { num_heartbeats=num_suspect_events=0; suspect_history.clear(); } public void init() throws Exception { timer=getTransport().getTimer(); if(timer == null) throw new Exception("timer cannot be retrieved"); } public void stop() { lock.lock(); try { stopMonitor(); } finally { lock.unlock(); } } private Address getPingDest(List<Address> mbrs) { Address tmp, retval=null; if(mbrs == null || mbrs.size() < 2 || local_addr == null) return null; for(int i=0; i < mbrs.size(); i++) { tmp=mbrs.get(i); if(local_addr.equals(tmp)) { if(i + 1 >= mbrs.size()) retval=mbrs.get(0); else retval=mbrs.get(i + 1); break; } } return retval; } /** Requires lock to held by caller */ @GuardedBy("lock") private void startMonitor() { if(monitor_future == null || monitor_future.isDone()) { last_ack=System.currentTimeMillis(); // start from scratch monitor_future=timer.scheduleWithFixedDelay(new Monitor(), timeout, timeout, TimeUnit.MILLISECONDS); num_tries=0; } } /** Requires lock to be held by caller */ @GuardedBy("lock") private void stopMonitor() { if(monitor_future != null) { monitor_future.cancel(true); monitor_future=null; } } /** Restarts the monitor if the ping destination has changed. If not, this is a no-op. * Requires lock to be held by the caller */ @GuardedBy("lock") private void restartMonitor() { Address tmp_dest=getPingDest(pingable_mbrs); boolean restart_monitor=tmp_dest == null || ping_dest == null || // tmp_dest != null && ping_dest == null !ping_dest.equals(tmp_dest); // tmp_dest != null && ping_dest != null if(restart_monitor) { ping_dest=tmp_dest; stopMonitor(); if(ping_dest != null) { try { startMonitor(); } catch(Exception ex) { if(log.isWarnEnabled()) log.warn("exception when calling startMonitor(): " + ex); } } } } public Object up(Event evt) { switch(evt.getType()) { case Event.SET_LOCAL_ADDRESS: local_addr=(Address)evt.getArg(); break; case Event.MSG: Message msg=(Message)evt.getArg(); FdHeader hdr=(FdHeader)msg.getHeader(name); if(hdr == null) { updateTimestamp(msg.getSrc()); break; // message did not originate from FD layer, just pass up } switch(hdr.type) { case FdHeader.HEARTBEAT: // heartbeat request; send heartbeat ack Address hb_sender=msg.getSrc(); if(log.isTraceEnabled()) log.trace("received are-you-alive from " + hb_sender + ", sending response"); sendHeartbeatResponse(hb_sender); // 2. Shun the sender of a HEARTBEAT message if that sender is not a member. This will cause // the sender to leave the group (and possibly rejoin it later) if(shun) shunInvalidHeartbeatSender(hb_sender); break; // don't pass up ! case FdHeader.HEARTBEAT_ACK: // heartbeat ack updateTimestamp(hdr.from); break; case FdHeader.SUSPECT: if(hdr.mbrs != null) { if(log.isTraceEnabled()) log.trace("[SUSPECT] suspect hdr is " + hdr); for(int i=0; i < hdr.mbrs.size(); i++) { Address m=hdr.mbrs.elementAt(i); if(local_addr != null && m.equals(local_addr)) { if(log.isWarnEnabled()) log.warn("I was suspected by " + msg.getSrc() + "; ignoring the SUSPECT " + "message and sending back a HEARTBEAT_ACK"); sendHeartbeatResponse(msg.getSrc()); continue; } else { lock.lock(); try { pingable_mbrs.remove(m); restartMonitor(); } finally { lock.unlock(); } } up_prot.up(new Event(Event.SUSPECT, m)); down_prot.down(new Event(Event.SUSPECT, m)); } } break; case FdHeader.NOT_MEMBER: if(shun) { if(log.isDebugEnabled()) log.debug("[NOT_MEMBER] I'm being shunned; exiting"); up_prot.up(new Event(Event.EXIT)); } break; } return null; } return up_prot.up(evt); // pass up to the layer above us } public Object down(Event evt) { switch(evt.getType()) { case Event.VIEW_CHANGE: down_prot.down(evt); lock.lock(); try { View v=(View)evt.getArg(); members.clear(); members.addAll(v.getMembers()); bcast_task.adjustSuspectedMembers(members); pingable_mbrs.clear(); pingable_mbrs.addAll(members); restartMonitor(); } finally { lock.unlock(); } return null; case Event.UNSUSPECT: unsuspect((Address)evt.getArg()); return down_prot.down(evt); } return down_prot.down(evt); } private void sendHeartbeatResponse(Address dest) { Message hb_ack=new Message(dest, null, null); hb_ack.setFlag(Message.OOB); FdHeader tmp_hdr=new FdHeader(FdHeader.HEARTBEAT_ACK); tmp_hdr.from=local_addr; hb_ack.putHeader(name, tmp_hdr); down_prot.down(new Event(Event.MSG, hb_ack)); } @GuardedBy("lock") private void unsuspect(Address mbr) { lock.lock(); try { bcast_task.removeSuspectedMember(mbr); pingable_mbrs.clear(); pingable_mbrs.addAll(members); pingable_mbrs.removeAll(bcast_task.getSuspectedMembers()); restartMonitor(); } finally { lock.unlock(); } } @GuardedBy("lock") private void updateTimestamp(Address sender) { lock.lock(); try { if(ping_dest != null && sender != null && ping_dest.equals(sender)) { last_ack=System.currentTimeMillis(); if(log.isTraceEnabled()) log.trace("received msg from " + sender + " (counts as ack)"); num_tries=0; } } finally { lock.unlock(); } } /** * If sender is not a member, send a NOT_MEMBER to sender (after n pings received) */ private void shunInvalidHeartbeatSender(Address hb_sender) { int num_pings=0; Message shun_msg=null; lock.lock(); try { if(hb_sender != null && members != null && !members.contains(hb_sender)) { if(invalid_pingers.containsKey(hb_sender)) { num_pings=invalid_pingers.get(hb_sender).intValue(); if(num_pings >= max_tries) { if(log.isDebugEnabled()) log.debug(hb_sender + " is not in " + members + " ! Shunning it"); shun_msg=new Message(hb_sender, null, null); shun_msg.setFlag(Message.OOB); shun_msg.putHeader(name, new FdHeader(FdHeader.NOT_MEMBER)); invalid_pingers.remove(hb_sender); } else { num_pings++; invalid_pingers.put(hb_sender, new Integer(num_pings)); } } else { num_pings++; invalid_pingers.put(hb_sender, new Integer(num_pings)); } } } finally { lock.unlock(); } if(shun_msg != null) down_prot.down(new Event(Event.MSG, shun_msg)); } public static class FdHeader extends Header implements Streamable { public static final byte HEARTBEAT=0; public static final byte HEARTBEAT_ACK=1; public static final byte SUSPECT=2; public static final byte NOT_MEMBER=3; // received as response by pinged mbr when we are not a member byte type=HEARTBEAT; Vector<Address> mbrs=null; Address from=null; // member who detected that suspected_mbr has failed private static final long serialVersionUID=-6387039473828820899L; public FdHeader() { } // used for externalization public FdHeader(byte type) { this.type=type; } public FdHeader(byte type, Vector<Address> mbrs, Address from) { this(type); this.mbrs=mbrs; this.from=from; } public String toString() { switch(type) { case HEARTBEAT: return "heartbeat"; case HEARTBEAT_ACK: return "heartbeat ack"; case SUSPECT: return "SUSPECT (suspected_mbrs=" + mbrs + ", from=" + from + ")"; case NOT_MEMBER: return "NOT_MEMBER"; default: return "unknown type (" + type + ")"; } } public void writeExternal(ObjectOutput out) throws IOException { out.writeByte(type); if(mbrs == null) out.writeBoolean(false); else { out.writeBoolean(true); out.writeInt(mbrs.size()); for(Iterator<Address> it=mbrs.iterator(); it.hasNext();) { Address addr=it.next(); out.writeObject(addr); } } out.writeObject(from); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { type=in.readByte(); boolean mbrs_not_null=in.readBoolean(); if(mbrs_not_null) { int len=in.readInt(); mbrs=new Vector<Address>(11); for(int i=0; i < len; i++) { Address addr=(Address)in.readObject(); mbrs.add(addr); } } from=(Address)in.readObject(); } public int size() { int retval=Global.BYTE_SIZE; // type retval+=Util.size(mbrs); retval+=Util.size(from); return retval; } public void writeTo(DataOutputStream out) throws IOException { out.writeByte(type); Util.writeAddresses(mbrs, out); Util.writeAddress(from, out); } public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { type=in.readByte(); mbrs=(Vector<Address>)Util.readAddresses(in, Vector.class); from=Util.readAddress(in); } } protected class Monitor implements Runnable { public void run() { Message hb_req; long not_heard_from; // time in msecs we haven't heard from ping_dest Address dest=null; lock.lock(); try { if(ping_dest == null) { if(log.isWarnEnabled()) log.warn("ping_dest is null: members=" + members + ", pingable_mbrs=" + pingable_mbrs + ", local_addr=" + local_addr); return; } else dest=ping_dest; } finally { lock.unlock(); } // 1. send heartbeat request hb_req=new Message(dest, null, null); hb_req.setFlag(Message.OOB); hb_req.putHeader(name, new FdHeader(FdHeader.HEARTBEAT)); // send heartbeat request if(log.isDebugEnabled()) log.debug("sending are-you-alive msg to " + dest + " (own address=" + local_addr + ')'); down_prot.down(new Event(Event.MSG, hb_req)); num_heartbeats++; // 2. If the time of the last heartbeat is > timeout and max_tries heartbeat messages have not been // received, then broadcast a SUSPECT message. Will be handled by coordinator, which may install // a new view not_heard_from=System.currentTimeMillis() - last_ack; // quick & dirty fix: increase timeout by 500msecs to allow for latency (bela June 27 2003) if(not_heard_from > timeout + 500) { // no heartbeat ack for more than timeout msecs if(num_tries >= max_tries) { if(log.isDebugEnabled()) log.debug("[" + local_addr + "]: received no heartbeat ack from " + dest + " for " + (num_tries +1) + " times (" + ((num_tries+1) * timeout) + " milliseconds), suspecting it"); // broadcast a SUSPECT message to all members - loop until // unsuspect or view change is received bcast_task.addSuspectedMember(dest); num_tries=0; if(stats) { num_suspect_events++; suspect_history.add(dest); } } else { if(log.isDebugEnabled()) log.debug("heartbeat missing from " + dest + " (number=" + num_tries + ')'); num_tries++; } } } } /** * Task that periodically broadcasts a list of suspected members to the group. Goal is not to lose * a SUSPECT message: since these are bcast unreliably, they might get dropped. The BroadcastTask makes * sure they are retransmitted until a view has been received which doesn't contain the suspected members * any longer. Then the task terminates. */ protected final class Broadcaster { final Vector<Address> suspected_mbrs=new Vector<Address>(7); final Lock bcast_lock=new ReentrantLock(); @GuardedBy("bcast_lock") Future<?> bcast_future=null; @GuardedBy("bcast_lock") BroadcastTask task; Vector<Address> getSuspectedMembers() { return suspected_mbrs; } /** * Starts a new task, or - if already running - adds the argument to the running task. * @param suspect */ private void startBroadcastTask(Address suspect) { bcast_lock.lock(); try { if(bcast_future == null || bcast_future.isDone()) { task=new BroadcastTask(suspected_mbrs); task.addSuspectedMember(suspect); bcast_future=timer.scheduleWithFixedDelay(task, 0, // run immediately the first time timeout, // then every timeout milliseconds, until cancelled TimeUnit.MILLISECONDS); if(log.isTraceEnabled()) log.trace("BroadcastTask started"); } else { task.addSuspectedMember(suspect); } } finally { bcast_lock.unlock(); } } private void stopBroadcastTask() { bcast_lock.lock(); try { if(bcast_future != null) { bcast_future.cancel(true); bcast_future=null; task=null; } } finally { bcast_lock.unlock(); } } /** Adds a suspected member. Starts the task if not yet running */ protected void addSuspectedMember(Address mbr) { if(mbr == null) return; if(!members.contains(mbr)) return; synchronized(suspected_mbrs) { if(!suspected_mbrs.contains(mbr)) { suspected_mbrs.addElement(mbr); startBroadcastTask(mbr); } } } void removeSuspectedMember(Address suspected_mbr) { if(suspected_mbr == null) return; if(log.isDebugEnabled()) log.debug("member is " + suspected_mbr); synchronized(suspected_mbrs) { suspected_mbrs.removeElement(suspected_mbr); if(suspected_mbrs.isEmpty()) stopBroadcastTask(); } } /** Removes all elements from suspected_mbrs that are <em>not</em> in the new membership */ void adjustSuspectedMembers(List<Address> new_mbrship) { if(new_mbrship == null || new_mbrship.isEmpty()) return; synchronized(suspected_mbrs) { suspected_mbrs.retainAll(new_mbrship); if(suspected_mbrs.isEmpty()) stopBroadcastTask(); } } } protected final class BroadcastTask implements Runnable { private final Vector<Address> suspected_members=new Vector<Address>(); BroadcastTask(Vector<Address> suspected_members) { this.suspected_members.addAll(suspected_members); } public void stop() { suspected_members.clear(); if(log.isTraceEnabled()) log.trace("BroadcastTask stopped"); } public void run() { Message suspect_msg; FD.FdHeader hdr; synchronized(suspected_members) { if(suspected_members.isEmpty()) { stop(); return; } hdr=new FdHeader(FdHeader.SUSPECT); hdr.mbrs=new Vector<Address>(suspected_members); hdr.from=local_addr; } suspect_msg=new Message(); // mcast SUSPECT to all members suspect_msg.setFlag(Message.OOB); suspect_msg.putHeader(name, hdr); if(log.isDebugEnabled()) log.debug("broadcasting SUSPECT message [suspected_mbrs=" + suspected_members + "] to group"); down_prot.down(new Event(Event.MSG, suspect_msg)); } public void addSuspectedMember(Address suspect) { if(suspect != null && !suspected_members.contains(suspect)) { suspected_members.add(suspect); } } } }
package at.outdated.bitcoin.exchange.api.market; import at.outdated.bitcoin.exchange.api.currency.Currency; import at.outdated.bitcoin.exchange.api.currency.CurrencyValue; import java.util.ArrayList; import java.util.Date; import java.util.List; public class MarketDepth { Date timestamp = new Date(); AssetPair asset; List<MarketOrder> bids = new ArrayList<>(); List<MarketOrder> asks = new ArrayList<>(); public MarketDepth() { } public MarketDepth(AssetPair asset) { setAsset(asset); } public MarketDepth(Currency base, Currency quote) { this.asset = new AssetPair(base, quote); } public void setAsset(AssetPair asset) { this.asset = asset; } public AssetPair getAsset() { return asset; } public List<MarketOrder> getBids() { return bids; } public List<MarketOrder> getAsks() { return asks; } public void addAsk(MarketOrder ask) { asks.add(ask); } public void addAsk(double volume, double price) { addAsk(new MarketOrder(TradeDecision.BUY, new CurrencyValue(volume, asset.getBase()), new CurrencyValue(price, asset.getQuote()))); } public void addBid(MarketOrder bid) { this.bids.add(bid); } public void addBid(double volume, double price) { addBid(new MarketOrder(TradeDecision.SELL, new CurrencyValue(volume, asset.getBase()), new CurrencyValue(price, asset.getQuote()))); } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } private String orderSummary(List<MarketOrder> orders) { if(orders == null || orders.isEmpty()) return "none"; CurrencyValue volumeSum = new CurrencyValue(0.0, orders.get(0).getVolume().getCurrency()); CurrencyValue priceSum = new CurrencyValue(0.0, orders.get(0).getPrice().getCurrency()); for(MarketOrder order : orders) { volumeSum.add(order.getVolume()); double volumePrice = order.getPrice().getValue() * order.getVolume().getValue(); priceSum.add(volumePrice); } return orders.size() + " orders (vol: " + volumeSum + " @ " + priceSum + ")"; } public CurrencyValue getPrice(TradeDecision decision, CurrencyValue volume) throws IllegalStateException { CurrencyValue price = null; if(volume.getCurrency() == asset.getBase()) { price = getAssetOrderPrice(decision, volume); } else { price = getReverseAssetOrderPrice(decision, volume); } return price; } public CurrencyValue getAssetOrderPrice(TradeDecision decision, CurrencyValue volume) throws IllegalStateException { assert(asset.getQuote() == volume.getCurrency()); Currency returnCurrency = asset.getOther(volume.getCurrency()); List<MarketOrder> orders = null; switch(decision) { case BUY: orders = getAsks(); break; case SELL: orders = getBids(); break; default: throw new IllegalArgumentException("cannot process TradeDecision " + decision); } CurrencyValue total = new CurrencyValue(0.0, returnCurrency); double remaining = volume.getValue(); for(MarketOrder order : orders) { // FIXME: what is the right thing here assert(order.getPrice().getCurrency() == volume.getCurrency()); double orderPrice = order.getPrice().getValue(); double additiveVol = order.getVolume().getValue(); if(additiveVol > remaining) { additiveVol = remaining; } // FIXME: this is probably wrong? total.add(additiveVol * orderPrice); remaining -= additiveVol; if(remaining < 0.00000001) break; } // FIXME: this should actually be exact 0 // TODO: use my own exception, return missing difference in exception to recalculate with less volume (find maximum tradeable volume) if(remaining > 0.00001) { throw new IllegalStateException("Insufficient market depth"); } return total; } protected CurrencyValue getReverseAssetOrderPrice(TradeDecision decision, CurrencyValue volume) throws IllegalStateException { assert(asset.getBase() == volume.getCurrency()); Currency returnCurrency = asset.getOther(volume.getCurrency()); List<MarketOrder> orders = null; // this is inverse to "normal" switch(decision) { case BUY: orders = getBids(); break; case SELL: orders = getAsks(); break; default: throw new IllegalArgumentException("cannot process TradeDecision " + decision); } CurrencyValue total = new CurrencyValue(0.0, returnCurrency); double remaining = volume.getValue(); for(MarketOrder order : orders) { // FIXME: what is the right thing here assert(order.getPrice().getCurrency() == volume.getCurrency()); double orderPrice = order.getPrice().getValue(); double orderVolume = order.getVolume().getValue(); double fullPrice = order.getVolume().getValue() * orderPrice; if(fullPrice > remaining) { orderVolume = remaining / orderPrice; fullPrice = orderVolume * orderPrice; } // FIXME: this is probably wrong? total.add(orderVolume); remaining -= fullPrice; if(remaining < 0.000001) break; } // FIXME: this should actually be exact 0 // TODO: use my own exception, return missing difference in exception to recalculate with less volume (find maximum tradeable volume) if(remaining > 0.000001) { throw new IllegalStateException("Insufficient market depth"); } return total; } @Override public String toString() { String bidSummary = orderSummary(bids); String askSummary = orderSummary(asks); return "Depth: bids: " + bidSummary + ", asks: " + askSummary; } }
package org.jgroups.protocols; import EDU.oswego.cs.dl.util.concurrent.BoundedLinkedQueue; import org.jgroups.*; import org.jgroups.stack.Protocol; import org.jgroups.util.*; import org.jgroups.util.List; import org.jgroups.util.Queue; import java.io.DataInputStream; import java.io.IOException; import java.net.*; import java.text.NumberFormat; import java.util.*; /** * Generic transport - specific implementations should extend this abstract class. * Features which are provided to the subclasses include * <ul> * <li>version checking * <li>marshalling and unmarshalling * <li>message bundling (handling single messages, and message lists) * <li>incoming packet handler * <li>loopback * </ul> * A subclass has to override * <ul> * <li>{@link #sendToAllMembers(byte[], int, int)} * <li>{@link #sendToSingleMember(org.jgroups.Address, byte[], int, int)} * <li>{@link #init()} * <li>{@link #start()}: subclasses <em>must</em> call super.start() <em>after</em> they initialize themselves * (e.g., created their sockets). * <li>{@link #stop()}: subclasses <em>must</em> call super.stop() after they deinitialized themselves * <li>{@link #destroy()} * </ul> * The create() or start() method has to create a local address.<br> * The {@link #receive(Address, Address, byte[], int, int)} method must * be called by subclasses when a unicast or multicast message has been received. * @author Bela Ban * @version $Id: TP.java,v 1.65 2006/05/22 20:31:32 belaban Exp $ */ public abstract class TP extends Protocol { /** The address (host and port) of this member */ protected Address local_addr=null; /** The name of the group to which this member is connected */ protected String channel_name=null; /** The interface (NIC) which should be used by this transport */ protected InetAddress bind_addr=null; /** Overrides bind_addr and -Dbind.address: let's the OS return the local host address */ boolean use_local_host=false; /** If true, the transport should use all available interfaces to receive multicast messages * @deprecated Use {@link receive_on_all_interfaces} instead */ boolean bind_to_all_interfaces=false; /** If true, the transport should use all available interfaces to receive multicast messages */ boolean receive_on_all_interfaces=false; /** List<NetworkInterface> of interfaces to receive multicasts on. The multicast receive socket will listen * on all of these interfaces. This is a comma-separated list of IP addresses or interface names. E.g. * "192.168.5.1,eth1,127.0.0.1". Duplicates are discarded; we only bind to an interface once. * If this property is set, it override receive_on_all_interfaces. */ java.util.List receive_interfaces=null; /** If true, the transport should use all available interfaces to send multicast messages. This means * the same multicast message is sent N times, so use with care */ boolean send_on_all_interfaces=false; /** List<NetworkInterface> of interfaces to send multicasts on. The multicast send socket will send the * same multicast message on all of these interfaces. This is a comma-separated list of IP addresses or * interface names. E.g. "192.168.5.1,eth1,127.0.0.1". Duplicates are discarded. * If this property is set, it override send_on_all_interfaces. */ java.util.List send_interfaces=null; /** The port to which the transport binds. 0 means to bind to any (ephemeral) port */ int bind_port=0; int port_range=1; // 27-6-2003 bgooren, Only try one port by default /** The members of this group (updated when a member joins or leaves) */ final protected Vector members=new Vector(11); protected View view=null; /** Pre-allocated byte stream. Used for marshalling messages. Will grow as needed */ final ExposedByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(1024); final ExposedBufferedOutputStream buf_out_stream=new ExposedBufferedOutputStream(out_stream, 1024); final ExposedDataOutputStream dos=new ExposedDataOutputStream(buf_out_stream); final ExposedByteArrayInputStream in_stream=new ExposedByteArrayInputStream(new byte[]{'0'}); final ExposedBufferedInputStream buf_in_stream=new ExposedBufferedInputStream(in_stream); final DataInputStream dis=new DataInputStream(buf_in_stream); /** If true, messages sent to self are treated specially: unicast messages are * looped back immediately, multicast messages get a local copy first and - * when the real copy arrives - it will be discarded. Useful for Window * media (non)sense */ boolean loopback=false; /** Discard packets with a different version. Usually minor version differences are okay. Setting this property * to true means that we expect the exact same version on all incoming packets */ boolean discard_incompatible_packets=false; /** Sometimes receivers are overloaded (they have to handle de-serialization etc). * Packet handler is a separate thread taking care of de-serialization, receiver * thread(s) simply put packet in queue and return immediately. Setting this to * true adds one more thread */ boolean use_incoming_packet_handler=true; /** Used by packet handler to store incoming DatagramPackets */ Queue incoming_packet_queue=null; /** Dequeues DatagramPackets from packet_queue, unmarshalls them and * calls <tt>handleIncomingUdpPacket()</tt> */ IncomingPacketHandler incoming_packet_handler=null; /** Used by packet handler to store incoming Messages */ Queue incoming_msg_queue=null; IncomingMessageHandler incoming_msg_handler; /** Packets to be sent are stored in outgoing_queue and sent by a separate thread. Enabling this * value uses an additional thread */ boolean use_outgoing_packet_handler=false; /** Used by packet handler to store outgoing DatagramPackets */ BoundedLinkedQueue outgoing_queue=null; /** max number of elements in the bounded outgoing_queue */ int outgoing_queue_max_size=2000; OutgoingPacketHandler outgoing_packet_handler=null; /** If set it will be added to <tt>local_addr</tt>. Used to implement * for example transport independent addresses */ byte[] additional_data=null; /** Maximum number of bytes for messages to be queued until they are sent. This value needs to be smaller than the largest datagram packet size in case of UDP */ int max_bundle_size=AUTOCONF.senseMaxFragSizeStatic(); /** Max number of milliseconds until queued messages are sent. Messages are sent when max_bundle_size or * max_bundle_timeout has been exceeded (whichever occurs faster) */ long max_bundle_timeout=20; /** Enabled bundling of smaller messages into bigger ones */ boolean enable_bundling=false; private Bundler bundler=null; protected TimeScheduler timer=null; private DiagnosticsHandler diag_handler=null; boolean enable_diagnostics=true; String diagnostics_addr="224.0.0.75"; int diagnostics_port=7500; /** HashMap<Address, Address>. Keys=senders, values=destinations. For each incoming message M with sender S, adds * an entry with key=S and value= sender's IP address and port. */ HashMap addr_translation_table=new HashMap(); boolean use_addr_translation=false; TpHeader header; final String name=getName(); static final byte LIST = 1; // we have a list of messages rather than a single message when set static final byte MULTICAST = 2; // message is a multicast (versus a unicast) message when set long num_msgs_sent=0, num_msgs_received=0, num_bytes_sent=0, num_bytes_received=0; static NumberFormat f; static { f=NumberFormat.getNumberInstance(); f.setGroupingUsed(false); f.setMaximumFractionDigits(2); } /** * Creates the TP protocol, and initializes the * state variables, does however not start any sockets or threads. */ protected TP() { } /** * debug only */ public String toString() { return name + "(local address: " + local_addr + ')'; } public void resetStats() { num_msgs_sent=num_msgs_received=num_bytes_sent=num_bytes_received=0; } public long getNumMessagesSent() {return num_msgs_sent;} public long getNumMessagesReceived() {return num_msgs_received;} public long getNumBytesSent() {return num_bytes_sent;} public long getNumBytesReceived() {return num_bytes_received;} public String getBindAddress() {return bind_addr != null? bind_addr.toString() : "null";} public void setBindAddress(String bind_addr) throws UnknownHostException { this.bind_addr=InetAddress.getByName(bind_addr); } /** @deprecated Use {@link #isReceiveOnAllInterfaces()} instead */ public boolean getBindToAllInterfaces() {return receive_on_all_interfaces;} public void setBindToAllInterfaces(boolean flag) {this.receive_on_all_interfaces=flag;} public boolean isReceiveOnAllInterfaces() {return receive_on_all_interfaces;} public java.util.List getReceiveInterfaces() {return receive_interfaces;} public boolean isSendOnAllInterfaces() {return send_on_all_interfaces;} public java.util.List getSendInterfaces() {return send_interfaces;} public boolean isDiscardIncompatiblePackets() {return discard_incompatible_packets;} public void setDiscardIncompatiblePackets(boolean flag) {discard_incompatible_packets=flag;} public boolean isEnableBundling() {return enable_bundling;} public void setEnableBundling(boolean flag) {enable_bundling=flag;} public int getMaxBundleSize() {return max_bundle_size;} public void setMaxBundleSize(int size) {max_bundle_size=size;} public long getMaxBundleTimeout() {return max_bundle_timeout;} public void setMaxBundleTimeout(long timeout) {max_bundle_timeout=timeout;} public int getOutgoingQueueSize() {return outgoing_queue != null? outgoing_queue.size() : 0;} public int getIncomingQueueSize() {return incoming_packet_queue != null? incoming_packet_queue.size() : 0;} public Address getLocalAddress() {return local_addr;} public String getChannelName() {return channel_name;} public boolean isLoopback() {return loopback;} public void setLoopback(boolean b) {loopback=b;} public boolean isUseIncomingPacketHandler() {return use_incoming_packet_handler;} public boolean isUseOutgoingPacketHandler() {return use_outgoing_packet_handler;} public int getOutgoingQueueMaxSize() {return outgoing_queue != null? outgoing_queue_max_size : 0;} public void setOutgoingQueueMaxSize(int new_size) { if(outgoing_queue != null) { outgoing_queue.setCapacity(new_size); outgoing_queue_max_size=new_size; } } public Map dumpStats() { Map retval=super.dumpStats(); if(retval == null) retval=new HashMap(); retval.put("num_msgs_sent", new Long(num_msgs_sent)); retval.put("num_msgs_received", new Long(num_msgs_received)); retval.put("num_bytes_sent", new Long(num_bytes_sent)); retval.put("num_bytes_received", new Long(num_bytes_received)); return retval; } /** * Send to all members in the group. UDP would use an IP multicast message, whereas TCP would send N * messages, one for each member * @param data The data to be sent. This is not a copy, so don't modify it * @param offset * @param length * @throws Exception */ public abstract void sendToAllMembers(byte[] data, int offset, int length) throws Exception; /** * Send to all members in the group. UDP would use an IP multicast message, whereas TCP would send N * messages, one for each member * @param dest Must be a non-null unicast address * @param data The data to be sent. This is not a copy, so don't modify it * @param offset * @param length * @throws Exception */ public abstract void sendToSingleMember(Address dest, byte[] data, int offset, int length) throws Exception; public abstract String getInfo(); public abstract void postUnmarshalling(Message msg, Address dest, Address src, boolean multicast); public abstract void postUnmarshallingList(Message msg, Address dest, boolean multicast); private StringBuffer _getInfo() { StringBuffer sb=new StringBuffer(); sb.append(local_addr).append(" (").append(channel_name).append(") ").append("\n"); sb.append("local_addr=").append(local_addr).append("\n"); sb.append("group_name=").append(channel_name).append("\n"); sb.append("Version=").append(Version.description).append(", cvs=\"").append(Version.cvs).append("\"\n"); sb.append("view: ").append(view).append('\n'); sb.append(getInfo()); return sb; } private void handleDiagnosticProbe(SocketAddress sender, DatagramSocket sock, String request) { try { StringTokenizer tok=new StringTokenizer(request); String req=tok.nextToken(); StringBuffer info=new StringBuffer("n/a"); if(req.trim().toLowerCase().startsWith("query")) { ArrayList l=new ArrayList(tok.countTokens()); while(tok.hasMoreTokens()) l.add(tok.nextToken().trim().toLowerCase()); info=_getInfo(); if(l.contains("jmx")) { Channel ch=stack.getChannel(); if(ch != null) { Map m=ch.dumpStats(); StringBuffer sb=new StringBuffer(); sb.append("stats:\n"); for(Iterator it=m.entrySet().iterator(); it.hasNext();) { sb.append(it.next()).append("\n"); } info.append(sb); } } if(l.contains("props")) { String p=stack.printProtocolSpecAsXML(); info.append("\nprops:\n").append(p); } } byte[] diag_rsp=info.toString().getBytes(); if(log.isDebugEnabled()) log.debug("sending diag response to " + sender); sendResponse(sock, sender, diag_rsp); } catch(Throwable t) { if(log.isErrorEnabled()) log.error("failed sending diag rsp to " + sender, t); } } private static void sendResponse(DatagramSocket sock, SocketAddress sender, byte[] buf) throws IOException { DatagramPacket p=new DatagramPacket(buf, 0, buf.length, sender); sock.send(p); } public void init() throws Exception { super.init(); if(bind_addr != null) { Map m=new HashMap(1); m.put("bind_addr", bind_addr); passUp(new Event(Event.CONFIG, m)); } } /** * Creates the unicast and multicast sockets and starts the unicast and multicast receiver threads */ public void start() throws Exception { timer=stack.timer; if(timer == null) throw new Exception("timer is null"); if(enable_diagnostics) { diag_handler=new DiagnosticsHandler(); diag_handler.start(); } if(use_incoming_packet_handler) { incoming_packet_queue=new Queue(); incoming_packet_handler=new IncomingPacketHandler(); incoming_packet_handler.start(); } if(loopback) { incoming_msg_queue=new Queue(); incoming_msg_handler=new IncomingMessageHandler(); incoming_msg_handler.start(); } if(use_outgoing_packet_handler) { outgoing_queue=new BoundedLinkedQueue(outgoing_queue_max_size); outgoing_packet_handler=new OutgoingPacketHandler(); outgoing_packet_handler.start(); } if(enable_bundling) { bundler=new Bundler(); } passUp(new Event(Event.SET_LOCAL_ADDRESS, local_addr)); } public void stop() { if(diag_handler != null) { diag_handler.stop(); diag_handler=null; } // 1. Stop the outgoing packet handler thread if(outgoing_packet_handler != null) outgoing_packet_handler.stop(); // 2. Stop the incoming packet handler thread if(incoming_packet_handler != null) incoming_packet_handler.stop(); // 3. Finally stop the incoming message handler if(incoming_msg_handler != null) incoming_msg_handler.stop(); } /** * Setup the Protocol instance according to the configuration string * @return true if no other properties are left. * false if the properties still have data in them, ie , * properties are left over and not handled by the protocol stack */ public boolean setProperties(Properties props) { String str; String tmp = null; super.setProperties(props); try { tmp=System.getProperty("bind.address"); if(Util.isBindAddressPropertyIgnored()) { tmp=null; } } catch (SecurityException ex){ } if(tmp != null) str=tmp; else str=props.getProperty("bind_addr"); if(str != null) { try { bind_addr=InetAddress.getByName(str); } catch(UnknownHostException unknown) { if(log.isFatalEnabled()) log.fatal("(bind_addr): host " + str + " not known"); return false; } props.remove("bind_addr"); } str=props.getProperty("use_local_host"); if(str != null) { use_local_host=new Boolean(str).booleanValue(); props.remove("use_local_host"); } str=props.getProperty("bind_to_all_interfaces"); if(str != null) { receive_on_all_interfaces=new Boolean(str).booleanValue(); props.remove("bind_to_all_interfaces"); log.warn("bind_to_all_interfaces has been deprecated; use receive_on_all_interfaces instead"); } str=props.getProperty("receive_on_all_interfaces"); if(str != null) { receive_on_all_interfaces=new Boolean(str).booleanValue(); props.remove("receive_on_all_interfaces"); } str=props.getProperty("receive_interfaces"); if(str != null) { try { receive_interfaces=parseInterfaceList(str); props.remove("receive_interfaces"); } catch(Exception e) { log.error("error determining interfaces (" + str + ")", e); return false; } } str=props.getProperty("send_on_all_interfaces"); if(str != null) { send_on_all_interfaces=new Boolean(str).booleanValue(); props.remove("send_on_all_interfaces"); } str=props.getProperty("send_interfaces"); if(str != null) { try { send_interfaces=parseInterfaceList(str); props.remove("send_interfaces"); } catch(Exception e) { log.error("error determining interfaces (" + str + ")", e); return false; } } str=props.getProperty("bind_port"); if(str != null) { bind_port=Integer.parseInt(str); props.remove("bind_port"); } str=props.getProperty("port_range"); if(str != null) { port_range=Integer.parseInt(str); props.remove("port_range"); } str=props.getProperty("loopback"); if(str != null) { loopback=Boolean.valueOf(str).booleanValue(); props.remove("loopback"); } str=props.getProperty("discard_incompatible_packets"); if(str != null) { discard_incompatible_packets=Boolean.valueOf(str).booleanValue(); props.remove("discard_incompatible_packets"); } // this is deprecated, just left for compatibility (use use_incoming_packet_handler) str=props.getProperty("use_packet_handler"); if(str != null) { use_incoming_packet_handler=Boolean.valueOf(str).booleanValue(); props.remove("use_packet_handler"); if(warn) log.warn("'use_packet_handler' is deprecated; use 'use_incoming_packet_handler' instead"); } str=props.getProperty("use_incoming_packet_handler"); if(str != null) { use_incoming_packet_handler=Boolean.valueOf(str).booleanValue(); props.remove("use_incoming_packet_handler"); } str=props.getProperty("use_outgoing_packet_handler"); if(str != null) { use_outgoing_packet_handler=Boolean.valueOf(str).booleanValue(); props.remove("use_outgoing_packet_handler"); } str=props.getProperty("outgoing_queue_max_size"); if(str != null) { outgoing_queue_max_size=Integer.parseInt(str); props.remove("outgoing_queue_max_size"); if(outgoing_queue_max_size <= 0) { if(log.isWarnEnabled()) log.warn("outgoing_queue_max_size of " + outgoing_queue_max_size + " is invalid, setting it to 1"); outgoing_queue_max_size=1; } } str=props.getProperty("max_bundle_size"); if(str != null) { int bundle_size=Integer.parseInt(str); if(bundle_size > max_bundle_size) { if(log.isErrorEnabled()) log.error("max_bundle_size (" + bundle_size + ") is greater than largest TP fragmentation size (" + max_bundle_size + ')'); return false; } if(bundle_size <= 0) { if(log.isErrorEnabled()) log.error("max_bundle_size (" + bundle_size + ") is <= 0"); return false; } max_bundle_size=bundle_size; props.remove("max_bundle_size"); } str=props.getProperty("max_bundle_timeout"); if(str != null) { max_bundle_timeout=Long.parseLong(str); if(max_bundle_timeout <= 0) { if(log.isErrorEnabled()) log.error("max_bundle_timeout of " + max_bundle_timeout + " is invalid"); return false; } props.remove("max_bundle_timeout"); } str=props.getProperty("enable_bundling"); if(str != null) { enable_bundling=Boolean.valueOf(str).booleanValue(); props.remove("enable_bundling"); } str=props.getProperty("use_addr_translation"); if(str != null) { use_addr_translation=Boolean.valueOf(str).booleanValue(); props.remove("use_addr_translation"); } str=props.getProperty("enable_diagnostics"); if(str != null) { enable_diagnostics=Boolean.valueOf(str).booleanValue(); props.remove("enable_diagnostics"); } str=props.getProperty("diagnostics_addr"); if(str != null) { diagnostics_addr=str; props.remove("diagnostics_addr"); } str=props.getProperty("diagnostics_port"); if(str != null) { diagnostics_port=Integer.parseInt(str); props.remove("diagnostics_port"); } if(enable_bundling) { //if (use_outgoing_packet_handler == false) // if(warn) log.warn("enable_bundling is true; setting use_outgoing_packet_handler=true"); // use_outgoing_packet_handler=true; } return true; } /** * This prevents the up-handler thread to be created, which essentially is superfluous: * messages are received from the network rather than from a layer below. * DON'T REMOVE ! */ public void startUpHandler() { } /** * handle the UP event. * @param evt - the event being send from the stack */ public void up(Event evt) { switch(evt.getType()) { case Event.CONFIG: passUp(evt); if(log.isDebugEnabled()) log.debug("received CONFIG event: " + evt.getArg()); handleConfigEvent((HashMap)evt.getArg()); return; } passUp(evt); } /** * Caller by the layer above this layer. Usually we just put this Message * into the send queue and let one or more worker threads handle it. A worker thread * then removes the Message from the send queue, performs a conversion and adds the * modified Message to the send queue of the layer below it, by calling down()). */ public void down(Event evt) { if(evt.getType() != Event.MSG) { // unless it is a message handle it and respond handleDownEvent(evt); return; } Message msg=(Message)evt.getArg(); if(header != null) { // added patch by Roland Kurmann (March 20 2003) // msg.putHeader(name, new TpHeader(channel_name)); msg.putHeader(name, header); } // Because we don't call Protocol.passDown(), we notify the observer directly (e.g. PerfObserver). // This way, we still have performance numbers for TP if(observer != null) observer.passDown(evt); setSourceAddress(msg); // very important !! listToBuffer() will fail with a null src address !! if(trace) { StringBuffer sb=new StringBuffer("sending msg to ").append(msg.getDest()). append(" (src=").append(msg.getSrc()).append("), headers are ").append(msg.getHeaders()); log.trace(sb.toString()); } // Don't send if destination is local address. Instead, switch dst and src and put in up_queue. // If multicast message, loopback a copy directly to us (but still multicast). Once we receive this, // we will discard our own multicast message Address dest=msg.getDest(); boolean multicast=dest == null || dest.isMulticastAddress(); if(loopback && (multicast || dest.equals(local_addr))) { Message copy=msg.copy(); // copy.removeHeader(name); // we don't remove the header copy.setSrc(local_addr); // copy.setDest(dest); if(trace) log.trace(new StringBuffer("looping back message ").append(copy)); try { incoming_msg_queue.add(copy); } catch(QueueClosedException e) { // log.error("failed adding looped back message to incoming_msg_queue", e); } if(!multicast) return; } try { if(use_outgoing_packet_handler) outgoing_queue.put(msg); else send(msg, dest, multicast); } catch(QueueClosedException closed_ex) { } catch(InterruptedException interruptedEx) { } catch(Throwable e) { if(log.isErrorEnabled()) log.error("failed sending message", e); } } /** * If the sender is null, set our own address. We cannot just go ahead and set the address * anyway, as we might be sending a message on behalf of someone else ! E.gin case of * retransmission, when the original sender has crashed, or in a FLUSH protocol when we * have to return all unstable messages with the FLUSH_OK response. */ private void setSourceAddress(Message msg) { if(msg.getSrc() == null) msg.setSrc(local_addr); } /** * Subclasses must call this method when a unicast or multicast message has been received. * Declared final so subclasses cannot override this method. * * @param dest * @param sender * @param data * @param offset * @param length */ protected final void receive(Address dest, Address sender, byte[] data, int offset, int length) { if(data == null) return; // if(length == 4) { // received a diagnostics probe // if(data[offset] == 'd' && data[offset+1] == 'i' && data[offset+2] == 'a' && data[offset+3] == 'g') { // handleDiagnosticProbe(sender); // return; boolean mcast=dest == null || dest.isMulticastAddress(); if(trace){ StringBuffer sb=new StringBuffer("received ("); sb.append(mcast? "mcast) " : "ucast) ").append(length).append(" bytes from ").append(sender); log.trace(sb.toString()); } try { if(use_incoming_packet_handler) { byte[] tmp=new byte[length]; System.arraycopy(data, offset, tmp, 0, length); incoming_packet_queue.add(new IncomingQueueEntry(dest, sender, tmp, offset, length)); } else handleIncomingPacket(dest, sender, data, offset, length); } catch(Throwable t) { if(log.isErrorEnabled()) log.error(new StringBuffer("failed handling data from ").append(sender), t); } } /** * Processes a packet read from either the multicast or unicast socket. Needs to be synchronized because * mcast or unicast socket reads can be concurrent. * Correction (bela April 19 2005): we access no instance variables, all vars are allocated on the stack, so * this method should be reentrant: removed 'synchronized' keyword */ private void handleIncomingPacket(Address dest, Address sender, byte[] data, int offset, int length) { Message msg=null; List l=null; // used if bundling is enabled short version; boolean is_message_list, multicast; byte flags; try { synchronized(in_stream) { in_stream.setData(data, offset, length); buf_in_stream.reset(length); version=dis.readShort(); if(Version.compareTo(version) == false) { if(warn) { StringBuffer sb=new StringBuffer(); sb.append("packet from ").append(sender).append(" has different version (").append(version); sb.append(") from ours (").append(Version.printVersion()).append("). "); if(discard_incompatible_packets) sb.append("Packet is discarded"); else sb.append("This may cause problems"); log.warn(sb); } if(discard_incompatible_packets) return; } flags=dis.readByte(); is_message_list=(flags & LIST) == LIST; multicast=(flags & MULTICAST) == MULTICAST; if(is_message_list) l=bufferToList(dis, dest, multicast); else msg=bufferToMessage(dis, dest, sender, multicast); } LinkedList msgs=new LinkedList(); if(is_message_list) { for(Enumeration en=l.elements(); en.hasMoreElements();) msgs.add(en.nextElement()); } else msgs.add(msg); Address src; for(Iterator it=msgs.iterator(); it.hasNext();) { msg=(Message)it.next(); src=msg.getSrc(); if(loopback) { if(multicast && src != null && local_addr.equals(src)) { // discard own loopback multicast packets it.remove(); } } else handleIncomingMessage(msg); } if(incoming_msg_queue != null && msgs.size() > 0) incoming_msg_queue.addAll(msgs); } catch(QueueClosedException closed_ex) { ; // swallow exception } catch(Throwable t) { if(log.isErrorEnabled()) log.error("failed unmarshalling message", t); } } private void handleIncomingMessage(Message msg) { Event evt; TpHeader hdr; if(stats) { num_msgs_received++; num_bytes_received+=msg.getLength(); } evt=new Event(Event.MSG, msg); if(trace) { StringBuffer sb=new StringBuffer("message is ").append(msg).append(", headers are ").append(msg.getHeaders()); log.trace(sb); } /* Because Protocol.up() is never called by this bottommost layer, we call up() directly in the observer. * This allows e.g. PerfObserver to get the time of reception of a message */ if(observer != null) observer.up(evt, up_queue.size()); hdr=(TpHeader)msg.getHeader(name); // replaced removeHeader() with getHeader() if(hdr != null) { /* Discard all messages destined for a channel with a different name */ String ch_name=hdr.channel_name; // Discard if message's group name is not the same as our group name unless the // message is a diagnosis message (special group name DIAG_GROUP) if(ch_name != null && channel_name != null && !channel_name.equals(ch_name) && !ch_name.equals(Util.DIAG_GROUP)) { if(warn) log.warn(new StringBuffer("discarded message from different group \"").append(ch_name). append("\" (our group is \"").append(channel_name).append("\"). Sender was").append(msg.getSrc())); return; } } else { if(trace) log.trace(new StringBuffer("message does not have a transport header, msg is ").append(msg). append(", headers are ").append(msg.getHeaders()).append(", will be discarded")); return; } passUp(evt); } /** Internal method to serialize and send a message. This method is not reentrant */ private void send(Message msg, Address dest, boolean multicast) throws Exception { if(enable_bundling) { bundler.send(msg, dest); return; } // Needs to be synchronized because we can have possible concurrent access, e.g. // Discovery uses a separate thread to send out discovery messages // We would *not* need to sync between send(), OutgoingPacketHandler and BundlingOutgoingPacketHandler, // because only *one* of them is enabled Buffer buf; synchronized(out_stream) { buf=messageToBuffer(msg, multicast); doSend(buf, dest, multicast); } } private void doSend(Buffer buf, Address dest, boolean multicast) throws Exception { if(stats) { num_msgs_sent++; num_bytes_sent+=buf.getLength(); } if(multicast) { sendToAllMembers(buf.getBuf(), buf.getOffset(), buf.getLength()); } else { sendToSingleMember(dest, buf.getBuf(), buf.getOffset(), buf.getLength()); } } /** * This method needs to be synchronized on out_stream when it is called * @param msg * @return * @throws java.io.IOException */ private Buffer messageToBuffer(Message msg, boolean multicast) throws Exception { Buffer retval; byte flags=0; out_stream.reset(); buf_out_stream.reset(out_stream.getCapacity()); dos.reset(); dos.writeShort(Version.version); // write the version if(multicast) flags+=MULTICAST; dos.writeByte(flags); // preMarshalling(msg, dest, src); // allows for optimization by subclass msg.writeTo(dos); // postMarshalling(msg, dest, src); // allows for optimization by subclass dos.flush(); retval=new Buffer(out_stream.getRawBuffer(), 0, out_stream.size()); return retval; } private Message bufferToMessage(DataInputStream instream, Address dest, Address sender, boolean multicast) throws Exception { Message msg=new Message(false); // don't create headers, readFrom() will do this msg.readFrom(instream); postUnmarshalling(msg, dest, sender, multicast); // allows for optimization by subclass return msg; } private Buffer listToBuffer(List l, boolean multicast) throws Exception { Buffer retval; Address src; Message msg; byte flags=0; int len=l != null? l.size() : 0; boolean src_written=false; out_stream.reset(); buf_out_stream.reset(out_stream.getCapacity()); dos.reset(); dos.writeShort(Version.version); flags+=LIST; if(multicast) flags+=MULTICAST; dos.writeByte(flags); dos.writeInt(len); for(Enumeration en=l.elements(); en.hasMoreElements();) { msg=(Message)en.nextElement(); src=msg.getSrc(); if(!src_written) { Util.writeAddress(src, dos); src_written=true; } // msg.setSrc(null); msg.writeTo(dos); // msg.setSrc(src); } dos.flush(); retval=new Buffer(out_stream.getRawBuffer(), 0, out_stream.size()); return retval; } private List bufferToList(DataInputStream instream, Address dest, boolean multicast) throws Exception { List l=new List(); DataInputStream in=null; int len; Message msg; Address src; try { len=instream.readInt(); src=Util.readAddress(instream); for(int i=0; i < len; i++) { msg=new Message(false); // don't create headers, readFrom() will do this msg.readFrom(instream); postUnmarshallingList(msg, dest, multicast); msg.setSrc(src); l.add(msg); } return l; } finally { Util.closeInputStream(in); } } /** * * @param s * @return List<NetworkInterface> */ private java.util.List parseInterfaceList(String s) throws Exception { java.util.List interfaces=new ArrayList(10); if(s == null) return null; StringTokenizer tok=new StringTokenizer(s, ","); String interface_name; NetworkInterface intf; while(tok.hasMoreTokens()) { interface_name=tok.nextToken(); // try by name first (e.g. (eth0") intf=NetworkInterface.getByName(interface_name); // next try by IP address or symbolic name if(intf == null) intf=NetworkInterface.getByInetAddress(InetAddress.getByName(interface_name)); if(intf == null) throw new Exception("interface " + interface_name + " not found"); if(interfaces.contains(intf)) { log.warn("did not add interface " + interface_name + " (already present in " + print(interfaces) + ")"); } else { interfaces.add(intf); } } return interfaces; } private static String print(java.util.List interfaces) { StringBuffer sb=new StringBuffer(); boolean first=true; NetworkInterface intf; for(Iterator it=interfaces.iterator(); it.hasNext();) { intf=(NetworkInterface)it.next(); if(first) { first=false; } else { sb.append(", "); } sb.append(intf.getName()); } return sb.toString(); } protected void handleDownEvent(Event evt) { switch(evt.getType()) { case Event.TMP_VIEW: case Event.VIEW_CHANGE: synchronized(members) { view=(View)evt.getArg(); members.clear(); Vector tmpvec=view.getMembers(); members.addAll(tmpvec); } break; case Event.GET_LOCAL_ADDRESS: // return local address -> Event(SET_LOCAL_ADDRESS, local) passUp(new Event(Event.SET_LOCAL_ADDRESS, local_addr)); break; case Event.CONNECT: channel_name=(String)evt.getArg(); header=new TpHeader(channel_name); setThreadNames(); // removed March 18 2003 (bela), not needed (handled by GMS) // changed July 2 2003 (bela): we discard CONNECT_OK at the GMS level anyway, this might // be needed if we run without GMS though passUp(new Event(Event.CONNECT_OK)); break; case Event.DISCONNECT: unsetThreadNames(); passUp(new Event(Event.DISCONNECT_OK)); break; case Event.CONFIG: if(log.isDebugEnabled()) log.debug("received CONFIG event: " + evt.getArg()); handleConfigEvent((HashMap)evt.getArg()); break; } } protected void setThreadNames() { if(channel_name != null) { String tmp, prefix=Global.THREAD_PREFIX; if(incoming_packet_handler != null) { tmp=incoming_packet_handler.getName(); if(tmp != null && tmp.indexOf(prefix) == -1) { tmp+=prefix + channel_name + ")"; incoming_packet_handler.setName(tmp); } } if(incoming_msg_handler != null) { tmp=incoming_msg_handler.getName(); if(tmp != null && tmp.indexOf(prefix) == -1) { tmp+=prefix + channel_name + ")"; incoming_msg_handler.setName(tmp); } } if(outgoing_packet_handler != null) { tmp=outgoing_packet_handler.getName(); if(tmp != null && tmp.indexOf(prefix) == -1) { tmp+=prefix + channel_name + ")"; outgoing_packet_handler.setName(tmp); } } if(diag_handler != null) { tmp=diag_handler.getName(); if(tmp != null && tmp.indexOf(prefix) == -1) { tmp+=prefix + channel_name + ")"; diag_handler.setName(tmp); } } } } protected void unsetThreadNames() { if(channel_name != null) { String tmp, prefix=Global.THREAD_PREFIX; int index; tmp=incoming_packet_handler != null? incoming_packet_handler.getName() : null; if(tmp != null) { index=tmp.indexOf(prefix); if(index > -1) { tmp=tmp.substring(0, index); incoming_packet_handler.setName(tmp); } } tmp=incoming_msg_handler != null? incoming_msg_handler.getName() : null; if(tmp != null) { index=tmp.indexOf(prefix); if(index > -1) { tmp=tmp.substring(0, index); incoming_msg_handler.setName(tmp); } } tmp=outgoing_packet_handler != null? outgoing_packet_handler.getName() : null; if(tmp != null) { index=tmp.indexOf(prefix); if(index > -1) { tmp=tmp.substring(0, index); outgoing_packet_handler.setName(tmp); } } tmp=diag_handler != null? diag_handler.getName() : null; if(tmp != null) { index=tmp.indexOf(prefix); if(index > -1) { tmp=tmp.substring(0, index); diag_handler.setName(tmp); } } } } protected void handleConfigEvent(HashMap map) { if(map == null) return; if(map.containsKey("additional_data")) additional_data=(byte[])map.get("additional_data"); } static class IncomingQueueEntry { Address dest=null; Address sender=null; byte[] buf; int offset, length; IncomingQueueEntry(Address dest, Address sender, byte[] buf, int offset, int length) { this.dest=dest; this.sender=sender; this.buf=buf; this.offset=offset; this.length=length; } } /** * This thread fetches byte buffers from the packet_queue, converts them into messages and passes them up * to the higher layer (done in handleIncomingUdpPacket()). */ class IncomingPacketHandler implements Runnable { Thread t=null; String getName() { return t != null? t.getName() : null; } void setName(String thread_name) { if(t != null) t.setName(thread_name); } void start() { if(t == null || !t.isAlive()) { t=new Thread(Util.getGlobalThreadGroup(), this, "IncomingPacketHandler"); t.setDaemon(true); t.start(); } } void stop() { incoming_packet_queue.close(true); // should terminate the packet_handler thread too t=null; } public void run() { IncomingQueueEntry entry; while(!incoming_packet_queue.closed() && Thread.currentThread().equals(t)) { try { entry=(IncomingQueueEntry)incoming_packet_queue.remove(); handleIncomingPacket(entry.dest, entry.sender, entry.buf, entry.offset, entry.length); } catch(QueueClosedException closed_ex) { break; } catch(Throwable ex) { if(log.isErrorEnabled()) log.error("error processing incoming packet", ex); } } if(trace) log.trace("incoming packet handler terminating"); } } class IncomingMessageHandler implements Runnable { Thread t; int i=0; String getName() { return t != null? t.getName() : null; } void setName(String thread_name) { if(t != null) t.setName(thread_name); } public void start() { if(t == null || !t.isAlive()) { t=new Thread(Util.getGlobalThreadGroup(), this, "IncomingMessageHandler"); t.setDaemon(true); t.start(); } } public void stop() { incoming_msg_queue.close(true); t=null; } public void run() { Message msg; while(!incoming_msg_queue.closed() && Thread.currentThread().equals(t)) { try { msg=(Message)incoming_msg_queue.remove(); handleIncomingMessage(msg); } catch(QueueClosedException closed_ex) { break; } catch(Throwable ex) { if(log.isErrorEnabled()) log.error("error processing incoming message", ex); } } if(trace) log.trace("incoming message handler terminating"); } } /** * This thread fetches byte buffers from the outgoing_packet_queue, converts them into messages and sends them * using the unicast or multicast socket */ class OutgoingPacketHandler implements Runnable { Thread t=null; byte[] buf; DatagramPacket packet; String getName() { return t != null? t.getName() : null; } void setName(String thread_name) { if(t != null) t.setName(thread_name); } void start() { if(t == null || !t.isAlive()) { t=new Thread(Util.getGlobalThreadGroup(), this, "OutgoingPacketHandler"); t.setDaemon(true); t.start(); } } void stop() { Thread tmp=t; t=null; if(tmp != null) { tmp.interrupt(); } } public void run() { Message msg; while(t != null && Thread.currentThread().equals(t)) { try { msg=(Message)outgoing_queue.take(); handleMessage(msg); } catch(QueueClosedException closed_ex) { break; } catch(InterruptedException interruptedEx) { } catch(Throwable th) { if(log.isErrorEnabled()) log.error("exception sending packet", th); } msg=null; // let's give the garbage collector a hand... this is probably useless though } if(trace) log.trace("outgoing message handler terminating"); } protected void handleMessage(Message msg) throws Throwable { Address dest=msg.getDest(); send(msg, dest, dest == null || dest.isMulticastAddress()); } } /** * Bundles smaller messages into bigger ones. Collects messages in a list until * messages of a total of <tt>max_bundle_size bytes</tt> have accumulated, or until * <tt>max_bundle_timeout</tt> milliseconds have elapsed, whichever is first. Messages * are unbundled at the receiver. */ // private class BundlingOutgoingPacketHandler extends OutgoingPacketHandler { // /** HashMap<Address, List<Message>>. Keys are destinations, values are lists of Messages */ // final HashMap msgs=new HashMap(11); // long count=0; // current number of bytes accumulated // int num_msgs=0; // long start=0; // long wait_time=0; // wait for removing messages from the queue // private void init() { // wait_time=start=count=0; // void start() { // init(); // super.start(); // t.setName("BundlingOutgoingPacketHandler"); // void stop() { // // bundleAndSend(); // super.stop(); // public void run() { // Message msg; // long length; // while(t != null && Thread.currentThread().equals(t)) { // try { // msg=(Message)outgoing_queue.poll(wait_time); // if(msg == null) // throw new TimeoutException(); // length=msg.size(); // checkLength(length); // if(start == 0) // start=System.currentTimeMillis(); // if(count + length >= max_bundle_size) { // bundleAndSend(); // count=0; // start=System.currentTimeMillis(); // addMessage(msg); // count+=length; // wait_time=max_bundle_timeout - (System.currentTimeMillis() - start); // if(wait_time <= 0) { // bundleAndSend(); // init(); // catch(QueueClosedException queue_closed_ex) { // bundleAndSend(); // break; // catch(TimeoutException timeout_ex) { // bundleAndSend(); // init(); // catch(Throwable ex) { // log.error("failure in bundling", ex); // if(trace) log.trace("BundlingOutgoingPacketHandler thread terminated"); // private void checkLength(long len) throws Exception { // if(len > max_bundle_size) // throw new Exception("message size (" + len + ") is greater than max bundling size (" + max_bundle_size + // "). Set the fragmentation/bundle size in FRAG and TP correctly"); // private void addMessage(Message msg) { // no sync needed, never called by multiple threads concurrently // List tmp; // Address dst=msg.getDest(); // tmp=(List)msgs.get(dst); // if(tmp == null) { // tmp=new List(); // msgs.put(dst, tmp); // tmp.add(msg); // num_msgs++; // private void bundleAndSend() { // Map.Entry entry; // Address dst; // Buffer buffer; // List l; // long stop_time=System.currentTimeMillis(); // if(msgs.size() == 0) // return; // try { // if(trace) { // StringBuffer sb=new StringBuffer("sending ").append(num_msgs).append(" msgs ("); // sb.append(count).append(" bytes, ").append(stop_time-start).append("ms)"); // sb.append(" to ").append(msgs.size()).append(" destination(s)"); // if(msgs.size() > 1) sb.append(" (dests=").append(msgs.keySet()).append(")"); // log.trace(sb.toString()); // boolean multicast; // for(Iterator it=msgs.entrySet().iterator(); it.hasNext();) { // entry=(Map.Entry)it.next(); // l=(List)entry.getValue(); // if(l.size() == 0) // continue; // dst=(Address)entry.getKey(); // multicast=dst == null || dst.isMulticastAddress(); // synchronized(out_stream) { // try { // buffer=listToBuffer(l, multicast); // doSend(buffer, dst, multicast); // catch(Throwable e) { // if(log.isErrorEnabled()) log.error("exception sending msg", e); // finally { // msgs.clear(); // num_msgs=0; private class Bundler { /** HashMap<Address, List<Message>>. Keys are destinations, values are lists of Messages */ final HashMap msgs=new HashMap(36); long count=0; // current number of bytes accumulated int num_msgs=0; long start=0; BundlingTimer bundling_timer=null; private synchronized void send(Message msg, Address dest) throws Exception { long length=msg.size(); checkLength(length); if(start == 0) start=System.currentTimeMillis(); if(count + length >= max_bundle_size) { cancelTimer(); bundleAndSend(); // clears msgs and resets num_msgs } addMessage(msg, dest); count+=length; startTimer(); // start timer if not running } /** Never called concurrently with cancelTimer - no need for synchronization */ private void startTimer() { if(bundling_timer == null || bundling_timer.cancelled()) { bundling_timer=new BundlingTimer(); timer.add(bundling_timer); } } /** Never called concurrently with startTimer() - no need for synchronization */ private void cancelTimer() { if(bundling_timer != null) { bundling_timer.cancel(); bundling_timer=null; } } private void addMessage(Message msg, Address dest) { // no sync needed, never called by multiple threads concurrently List tmp; synchronized(msgs) { tmp=(List)msgs.get(dest); if(tmp == null) { tmp=new List(); msgs.put(dest, tmp); } tmp.add(msg); num_msgs++; } } private void bundleAndSend() { Map.Entry entry; Address dst; Buffer buffer; List l; synchronized(msgs) { if(msgs.size() == 0) return; try { if(trace) { long stop=System.currentTimeMillis(); double percentage=100.0 / max_bundle_size * count; StringBuffer sb=new StringBuffer("sending ").append(num_msgs).append(" msgs ("); sb.append(count).append(" bytes (" + f.format(percentage) + "% of max_bundle_size), collected in "+ + (stop-start) + "ms) to ").append(msgs.size()). append(" destination(s)"); if(msgs.size() > 1) sb.append(" (dests=").append(msgs.keySet()).append(")"); log.trace(sb.toString()); } boolean multicast; for(Iterator it=msgs.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); l=(List)entry.getValue(); if(l.size() == 0) continue; dst=(Address)entry.getKey(); multicast=dst == null || dst.isMulticastAddress(); synchronized(out_stream) { try { buffer=listToBuffer(l, multicast); doSend(buffer, dst, multicast); } catch(Throwable e) { if(log.isErrorEnabled()) log.error("exception sending msg", e); } } } } finally { msgs.clear(); num_msgs=0; start=0; count=0; } } } private void checkLength(long len) throws Exception { if(len > max_bundle_size) throw new Exception("message size (" + len + ") is greater than max bundling size (" + max_bundle_size + "). Set the fragmentation/bundle size in FRAG and TP correctly"); } private class BundlingTimer implements TimeScheduler.Task { boolean cancelled=false; void cancel() { cancelled=true; } public boolean cancelled() { return cancelled; } public long nextInterval() { return max_bundle_timeout; } public void run() { bundleAndSend(); cancelled=true; } } } private class DiagnosticsHandler implements Runnable { Thread t=null; MulticastSocket diag_sock=null; DiagnosticsHandler() { } String getName() { return t != null? t.getName() : null; } void setName(String thread_name) { if(t != null) t.setName(thread_name); } void start() throws IOException { diag_sock=new MulticastSocket(diagnostics_port); java.util.List interfaces=Util.getAllAvailableInterfaces(); bindToInterfaces(interfaces, diag_sock); if(t == null || !t.isAlive()) { t=new Thread(Util.getGlobalThreadGroup(), this, "DiagnosticsHandler"); t.setDaemon(true); t.start(); } } void stop() { if(diag_sock != null) diag_sock.close(); t=null; } public void run() { byte[] buf=new byte[1500]; // MTU on most LANs DatagramPacket packet; while(!diag_sock.isClosed() && Thread.currentThread().equals(t)) { packet=new DatagramPacket(buf, 0, buf.length); try { diag_sock.receive(packet); handleDiagnosticProbe(packet.getSocketAddress(), diag_sock, new String(packet.getData(), packet.getOffset(), packet.getLength())); } catch(IOException e) { } } } private void bindToInterfaces(java.util.List interfaces, MulticastSocket s) { SocketAddress group_addr=new InetSocketAddress(diagnostics_addr, diagnostics_port); for(Iterator it=interfaces.iterator(); it.hasNext();) { NetworkInterface i=(NetworkInterface)it.next(); try { if (i.getInetAddresses().hasMoreElements()) { // fix for VM crash - suggested by JJalenak@netopia.com s.joinGroup(group_addr, i); if(trace) log.trace("joined " + group_addr + " on " + i.getName()); } } catch(IOException e) { log.warn("failed to join " + group_addr + " on " + i.getName() + ": " + e); } } } } }
package com.bitsofproof.supernode.wallet; import java.io.PrintStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.bitsofproof.supernode.api.Transaction; import com.bitsofproof.supernode.api.TransactionInput; import com.bitsofproof.supernode.api.TransactionOutput; import com.bitsofproof.supernode.common.ByteUtils; import com.bitsofproof.supernode.common.ByteVector; import com.bitsofproof.supernode.common.ECKeyPair; import com.bitsofproof.supernode.common.Key; import com.bitsofproof.supernode.common.ScriptFormat; import com.bitsofproof.supernode.common.ScriptFormat.Opcode; import com.bitsofproof.supernode.common.ValidationException; import com.bitsofproof.supernode.common.WireFormat; public abstract class BaseAccountManager implements AccountManager { private static final Logger log = LoggerFactory.getLogger (BaseAccountManager.class); private static final long MINIMUM_FEE = 10000; private static final long MAXIMUM_FEE = 1000000; private UTXO confirmed = createConfirmedUTXO (); private UTXO change = createChangeUTXO (); private UTXO receiving = createReceivingUTXO (); private UTXO sending = createSendingUTXO (); private long created; @Override public long getCreated () { return created; } public void setCreated (long created) { this.created = created; } private final List<AccountListener> accountListener = Collections.synchronizedList (new ArrayList<AccountListener> ()); private final Map<String, Transaction> transactions = new HashMap<String, Transaction> (); protected UTXO createConfirmedUTXO () { return new InMemoryUTXO (); } protected UTXO createChangeUTXO () { return new InMemoryUTXO (); } protected UTXO createSendingUTXO () { return new InMemoryUTXO (); } protected UTXO createReceivingUTXO () { return new InMemoryUTXO (); } protected void reset () { confirmed = createConfirmedUTXO (); change = createChangeUTXO (); receiving = createReceivingUTXO (); sending = createSendingUTXO (); } public boolean isOwnAddress (byte[] address) { return getKeyForAddress (address) != null; } protected static class TransactionSink { private final Address address; private final long value; public TransactionSink (Address address, long value) { super (); this.address = address; this.value = value; } public Address getAddress () { return address; } public long getValue () { return value; } } public static long estimateFee (Transaction t) { WireFormat.Writer writer = new WireFormat.Writer (); t.toWire (writer); return Math.min (MAXIMUM_FEE, Math.max (MINIMUM_FEE, writer.toByteArray ().length / 1000 * MINIMUM_FEE)); } protected Transaction createSpend (List<TransactionOutput> sources, List<TransactionSink> sinks, long fee) throws ValidationException { if ( fee < 0 || fee > MAXIMUM_FEE ) { throw new ValidationException ("You unlikely want to do that"); } Transaction transaction = new Transaction (); transaction.setInputs (new ArrayList<TransactionInput> ()); transaction.setOutputs (new ArrayList<TransactionOutput> ()); long sumOut = 0; for ( TransactionSink s : sinks ) { TransactionOutput o = new TransactionOutput (); o.setValue (s.getValue ()); sumOut += s.getValue (); ScriptFormat.Writer writer = new ScriptFormat.Writer (); if ( s.getAddress ().getType () == Address.Type.COMMON ) { writer.writeToken (new ScriptFormat.Token (Opcode.OP_DUP)); writer.writeToken (new ScriptFormat.Token (Opcode.OP_HASH160)); writer.writeData (s.getAddress ().getAddress ()); writer.writeToken (new ScriptFormat.Token (Opcode.OP_EQUALVERIFY)); writer.writeToken (new ScriptFormat.Token (Opcode.OP_CHECKSIG)); } else if ( s.getAddress ().getType () == Address.Type.P2SH ) { writer.writeToken (new ScriptFormat.Token (Opcode.OP_HASH160)); writer.writeData (s.getAddress ().getAddress ()); writer.writeToken (new ScriptFormat.Token (Opcode.OP_EQUAL)); } else { throw new ValidationException ("unknown sink address type"); } o.setScript (writer.toByteArray ()); transaction.getOutputs ().add (o); } long sumInput = 0; for ( TransactionOutput o : sources ) { TransactionInput i = new TransactionInput (); i.setSourceHash (o.getTxHash ()); i.setIx (o.getIx ()); sumInput += o.getValue (); transaction.getInputs ().add (i); } if ( sumInput != (sumOut + fee) ) { throw new ValidationException ("Sum of sinks (+fee) does not match sum of sources"); } int j = 0; for ( TransactionOutput s : sources ) { TransactionInput i = transaction.getInputs ().get (j); ScriptFormat.Writer sw = new ScriptFormat.Writer (); if ( ScriptFormat.isPayToAddress (s.getScript ()) ) { byte[] address = s.getOutputAddress (); Key key = getKeyForAddress (address); if ( key == null ) { throw new ValidationException ("Have no key to spend this output"); } byte[] sig = key.sign (hashTransaction (transaction, j, ScriptFormat.SIGHASH_ALL, s.getScript ())); byte[] sigPlusType = new byte[sig.length + 1]; System.arraycopy (sig, 0, sigPlusType, 0, sig.length); sigPlusType[sigPlusType.length - 1] = (byte) (ScriptFormat.SIGHASH_ALL & 0xff); sw.writeData (sigPlusType); sw.writeData (key.getPublic ()); } else { spendNonAddressOutput (j, s, sw, transaction); } i.setScript (sw.toByteArray ()); ++j; } transaction.computeHash (); return transaction; } protected void spendNonAddressOutput (int ix, TransactionOutput source, ScriptFormat.Writer writer, Transaction transaction) throws ValidationException { throw new ValidationException ("Can not spend this output type"); } public static byte[] hashTransaction (Transaction transaction, int inr, int hashType, byte[] script) throws ValidationException { Transaction copy = null; try { copy = transaction.clone (); } catch ( CloneNotSupportedException e1 ) { return null; } // implicit SIGHASH_ALL int i = 0; for ( TransactionInput in : copy.getInputs () ) { if ( i == inr ) { in.setScript (script); } else { in.setScript (new byte[0]); } ++i; } if ( (hashType & 0x1f) == ScriptFormat.SIGHASH_NONE ) { copy.getOutputs ().clear (); i = 0; for ( TransactionInput in : copy.getInputs () ) { if ( i != inr ) { in.setSequence (0); } ++i; } } else if ( (hashType & 0x1f) == ScriptFormat.SIGHASH_SINGLE ) { int onr = inr; if ( onr >= copy.getOutputs ().size () ) { // this is a Satoshi client bug. // This case should throw an error but it instead retuns 1 that is not checked and interpreted as below return ByteUtils.fromHex ("0100000000000000000000000000000000000000000000000000000000000000"); } for ( i = copy.getOutputs ().size () - 1; i > onr; --i ) { copy.getOutputs ().remove (i); } for ( i = 0; i < onr; ++i ) { copy.getOutputs ().get (i).setScript (new byte[0]); copy.getOutputs ().get (i).setValue (-1L); } i = 0; for ( TransactionInput in : copy.getInputs () ) { if ( i != inr ) { in.setSequence (0); } ++i; } } if ( (hashType & ScriptFormat.SIGHASH_ANYONECANPAY) != 0 ) { List<TransactionInput> oneIn = new ArrayList<TransactionInput> (); oneIn.add (copy.getInputs ().get (inr)); copy.setInputs (oneIn); } WireFormat.Writer writer = new WireFormat.Writer (); copy.toWire (writer); byte[] txwire = writer.toByteArray (); byte[] hash = null; try { MessageDigest a = MessageDigest.getInstance ("SHA-256"); a.update (txwire); a.update (new byte[] { (byte) (hashType & 0xff), 0, 0, 0 }); hash = a.digest (a.digest ()); } catch ( NoSuchAlgorithmException e ) { } return hash; } protected List<TransactionOutput> getSufficientSources (long amount, long fee, String color) { List<TransactionOutput> candidates = new ArrayList<TransactionOutput> (); candidates.addAll (confirmed.getUTXO ()); // prefer confirmed Collections.sort (candidates, new Comparator<TransactionOutput> () { // prefer aggregation of UTXO @Override public int compare (TransactionOutput o1, TransactionOutput o2) { return (int) (o1.getValue () - o2.getValue ()); } }); List<TransactionOutput> changelist = new ArrayList<TransactionOutput> (); changelist.addAll (change.getUTXO ()); // ... then change Collections.sort (changelist, new Comparator<TransactionOutput> () { // prefer aggregation of UTXO @Override public int compare (TransactionOutput o1, TransactionOutput o2) { return (int) (o1.getValue () - o2.getValue ()); } }); candidates.addAll (changelist); List<TransactionOutput> result = new ArrayList<TransactionOutput> (); long sum = 0; for ( TransactionOutput o : candidates ) { if ( color == null ) { if ( o.getColor () == null ) { sum += o.getValue (); result.add (o); if ( sum >= (amount + fee) ) { return result; } } } else { if ( o.getColor ().equals (color) ) { sum += o.getValue (); result.add (o); if ( sum >= amount ) { if ( fee > 0 ) { result.addAll (getSufficientSources (0, fee, null)); } return result; } } } } return null; } @Override public Address getNextAddress () throws ValidationException { return new Address (Address.Network.PRODUCTION, Address.Type.COMMON, getNextKey ().getAddress ()); } @Override public Transaction pay (Address receiver, long amount, long fee) throws ValidationException { List<Address> a = new ArrayList<Address> (); a.add (receiver); List<Long> v = new ArrayList<Long> (); v.add (amount); return pay (a, v, fee, true); } @Override public Transaction pay (List<Address> receiver, List<Long> amounts, long fee, boolean senderPaysfee) throws ValidationException { synchronized ( confirmed ) { long amount = 0; for ( Long a : amounts ) { amount += a; } log.trace ("pay " + amount + (senderPaysfee ? " " + fee : "")); List<TransactionOutput> sources; if ( senderPaysfee ) { sources = getSufficientSources (amount, fee, null); } else { sources = getSufficientSources (amount, 0, null); } if ( sources == null ) { throw new ValidationException ("Insufficient funds to pay " + (amount + (senderPaysfee ? fee : 0))); } long in = 0; for ( TransactionOutput o : sources ) { log.trace ("using input " + o.getTxHash () + "[" + o.getIx () + "] " + o.getValue ()); in += o.getValue (); } List<TransactionSink> sinks = new ArrayList<TransactionSink> (); Iterator<Long> ai = amounts.iterator (); for ( Address r : receiver ) { sinks.add (new TransactionSink (r, ai.next () - (!senderPaysfee ? (fee + receiver.size () - 1) / receiver.size () : 0))); } if ( (in - amount - fee) > 0 ) { TransactionSink change = new TransactionSink (getNextAddress (), in - amount - (senderPaysfee ? fee : 0)); log.trace ("change to " + change.getAddress () + " " + change.getValue ()); sinks.add (change); } Collections.shuffle (sinks); return createSpend (sources, sinks, fee); } } @Override public Transaction pay (byte[] receiver, long amount, long fee) throws ValidationException { return pay (new Address (Address.Network.PRODUCTION, Address.Type.COMMON, receiver), amount, fee); } @Override public Transaction pay (Address receiver, long amount, boolean senderPaysFee) throws ValidationException { List<Address> a = new ArrayList<Address> (); a.add (receiver); List<Long> v = new ArrayList<Long> (); v.add (amount); return pay (a, v, senderPaysFee); } @Override public Transaction pay (List<Address> receiver, List<Long> amounts, boolean senderPaysfee) throws ValidationException { long fee = MINIMUM_FEE; long estimate = 0; Transaction t = null; do { fee = Math.max (fee, estimate); t = pay (receiver, amounts, fee, senderPaysfee); estimate = estimateFee (t); if ( fee < estimate ) { log.trace ("The transaction requires more network fees. Reassembling."); } } while ( fee < estimate ); return t; } @Override public Transaction pay (byte[] receiver, long amount) throws ValidationException { return pay (new Address (Address.Network.PRODUCTION, Address.Type.COMMON, receiver), amount, true); } @Override public Transaction split (long[] amounts, long fee) throws ValidationException { synchronized ( confirmed ) { List<TransactionSink> sinks = new ArrayList<TransactionSink> (); long amount = 0; for ( long a : amounts ) { amount += a; } List<TransactionOutput> sources = getSufficientSources (amount, fee, null); if ( sources == null ) { throw new ValidationException ("Insufficient funds to pay " + (amount + fee)); } long in = 0; for ( TransactionOutput o : sources ) { in += o.getValue (); } for ( long a : amounts ) { TransactionSink target = new TransactionSink (getNextAddress (), a); sinks.add (target); } if ( (in - amount - fee) > 0 ) { TransactionSink change = new TransactionSink (getNextAddress (), in - amount - fee); sinks.add (change); } Collections.shuffle (sinks); return createSpend (sources, sinks, fee); } } public boolean updateWithTransaction (Transaction t) { synchronized ( confirmed ) { boolean modified = false; if ( !t.isDoubleSpend () ) { TransactionOutput spend = null; for ( TransactionInput i : t.getInputs () ) { spend = confirmed.get (i.getSourceHash (), i.getIx ()); if ( spend != null ) { confirmed.remove (i.getSourceHash (), i.getIx ()); log.trace ("Spend settled output " + i.getSourceHash () + " [" + i.getIx () + "] " + spend.getValue ()); } else { spend = change.get (i.getSourceHash (), i.getIx ()); if ( spend != null ) { change.remove (i.getSourceHash (), i.getIx ()); log.trace ("Spend change output " + i.getSourceHash () + " [" + i.getIx () + "] " + spend.getValue ()); } else { spend = receiving.get (i.getSourceHash (), i.getIx ()); if ( spend != null ) { receiving.remove (i.getSourceHash (), i.getIx ()); log.trace ("Spend receiving output " + i.getSourceHash () + " [" + i.getIx () + "] " + spend.getValue ()); } } } } modified = spend != null; for ( TransactionOutput o : t.getOutputs () ) { confirmed.remove (o.getTxHash (), o.getIx ()); change.remove (o.getTxHash (), o.getIx ()); receiving.remove (o.getTxHash (), o.getIx ()); sending.remove (o.getTxHash (), o.getIx ()); if ( isOwnAddress (o.getOutputAddress ()) ) { modified = true; if ( t.getBlockHash () != null ) { confirmed.add (o); log.trace ("Settled " + t.getHash () + " [" + o.getIx () + "] (" + ByteUtils.toHex (o.getOutputAddress ()) + ") " + o.getValue ()); } else { if ( spend != null ) { change.add (o); log.trace ("Change " + t.getHash () + " [" + o.getIx () + "] (" + ByteUtils.toHex (o.getOutputAddress ()) + ") " + o.getValue ()); } else { receiving.add (o); log.trace ("Receiving " + t.getHash () + " [" + o.getIx () + "] (" + ByteUtils.toHex (o.getOutputAddress ()) + ") " + o.getValue ()); } } } else { if ( t.getBlockHash () == null && spend != null ) { modified = true; sending.add (o); log.trace ("Sending " + t.getHash () + " [" + o.getIx () + "] (" + ByteUtils.toHex (o.getOutputAddress ()) + ") " + o.getValue ()); } } } if ( modified ) { transactions.put (t.getHash (), t); } } else { for ( long ix = 0; ix < t.getOutputs ().size (); ++ix ) { TransactionOutput out = null; out = confirmed.remove (t.getHash (), ix); if ( out == null ) { out = change.remove (t.getHash (), ix); } if ( out == null ) { out = receiving.remove (t.getHash (), ix); } if ( out == null ) { out = sending.remove (t.getHash (), ix); } if ( out != null ) { log.trace ("Remove DS " + out.getTxHash () + " [" + out.getIx () + "] (" + ByteUtils.toHex (out.getOutputAddress ()) + ")" + out.getValue ()); } modified |= out != null; } transactions.remove (t.getHash ()); } return modified; } } @Override public long getBalance () { synchronized ( confirmed ) { return confirmed.getTotal () + change.getTotal () + receiving.getTotal (); } } @Override public long getConfirmed () { synchronized ( confirmed ) { return confirmed.getTotal (); } } @Override public long getSending () { synchronized ( confirmed ) { return sending.getTotal (); } } @Override public long getReceiving () { synchronized ( confirmed ) { return receiving.getTotal (); } } @Override public long getChange () { synchronized ( confirmed ) { return change.getTotal (); } } @Override public Collection<TransactionOutput> getConfirmedOutputs () { return confirmed.getUTXO (); } @Override public Collection<TransactionOutput> getSendingOutputs () { return sending.getUTXO (); } @Override public Collection<TransactionOutput> getReceivingOutputs () { return receiving.getUTXO (); } @Override public Collection<TransactionOutput> getChangeOutputs () { return change.getUTXO (); } @Override public void addAccountListener (AccountListener listener) { accountListener.add (listener); } @Override public void removeAccountListener (AccountListener listener) { accountListener.remove (listener); } protected void notifyListener (Transaction t) { synchronized ( accountListener ) { for ( AccountListener l : accountListener ) { try { l.accountChanged (this, t); } catch ( Exception e ) { } } } } @Override public void process (Transaction t) { if ( updateWithTransaction (t) ) { notifyListener (t); } } @Override public List<Transaction> getTransactions () { List<Transaction> tl = new ArrayList<Transaction> (); tl.addAll (transactions.values ()); Collections.sort (tl, new Comparator<Transaction> () { @Override public int compare (Transaction a, Transaction b) { for ( TransactionInput i : b.getInputs () ) { if ( i.getSourceHash ().equals (a.getHash ()) ) { return -1; } } for ( TransactionInput i : a.getInputs () ) { if ( i.getSourceHash ().equals (b.getHash ()) ) { return 1; } } return 0; } }); return tl; } public void dumpOutputs (PrintStream print) { print.println ("Confirmed:"); dumpUTXO (print, confirmed); print.println ("Receiving:"); dumpUTXO (print, receiving); print.println ("Change:"); dumpUTXO (print, change); print.println ("Sending:"); dumpUTXO (print, sending); } public void dumpKeys (PrintStream print) { Set<ByteVector> addresses = new HashSet<ByteVector> (); for ( TransactionOutput o : confirmed.getUTXO () ) { addresses.add (new ByteVector (o.getOutputAddress ())); } for ( TransactionOutput o : change.getUTXO () ) { addresses.add (new ByteVector (o.getOutputAddress ())); } for ( TransactionOutput o : receiving.getUTXO () ) { addresses.add (new ByteVector (o.getOutputAddress ())); } for ( ByteVector b : addresses ) { Key k = getKeyForAddress (b.toByteArray ()); if ( k != null ) { print.println (ECKeyPair.serializeWIF (k) + " (" + ByteUtils.toHex (b.toByteArray ()) + ")"); } } } private void dumpUTXO (PrintStream print, UTXO set) { for ( TransactionOutput o : set.getUTXO () ) { print.println (o.getTxHash () + "[" + o.getIx () + "] (" + ByteUtils.toHex (o.getOutputAddress ()) + ") " + o.getValue ()); } print.println (); } }
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Main { private static Scanner sc; static FileWriter fw; static BufferedWriter bf; /** * @param args */ public static void main(String[] args) { instanciarFichero(); } /** * Metodo que Instancia el Fichero */ private static void instanciarFichero() { String ruta = "fichero.txt"; File f = new File(ruta); try { fw = new FileWriter(f); bf = new BufferedWriter(fw); System.out.println("Introduzca un Numero"); sc = new Scanner(System.in); int m= sc.nextInt(); calcularFibonacci(m); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Metodo que Calcula la serie Fibonacci y la escribe en el Fichero * @param m */ public static void calcularFibonacci(int m){ int acumulador = 1; int acumulador2 = 0; for (int i = 0; i < m; i++) { int total = acumulador + acumulador2; acumulador2 = acumulador; acumulador = total; String acu = Integer.toString(acumulador2); try { bf.write(acu); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { bf.newLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { bf.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package org.jgroups.protocols; import org.jgroups.*; import org.jgroups.blocks.LazyRemovalCache; import org.jgroups.annotations.*; import org.jgroups.conf.PropertyConverters; import org.jgroups.stack.Protocol; import org.jgroups.util.*; import org.jgroups.util.ThreadFactory; import org.jgroups.util.UUID; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.*; import java.text.NumberFormat; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Generic transport - specific implementations should extend this abstract class. * Features which are provided to the subclasses include * <ul> * <li>version checking * <li>marshalling and unmarshalling * <li>message bundling (handling single messages, and message lists) * <li>incoming packet handler * <li>loopback * </ul> * A subclass has to override * <ul> * <li>{@link #sendMulticast(byte[], int, int)} * <li>{@link #sendUnicast(org.jgroups.PhysicalAddress, byte[], int, int)} * <li>{@link #init()} * <li>{@link #start()}: subclasses <em>must</em> call super.start() <em>after</em> they initialize themselves * (e.g., created their sockets). * <li>{@link #stop()}: subclasses <em>must</em> call super.stop() after they deinitialized themselves * <li>{@link #destroy()} * </ul> * The create() or start() method has to create a local address.<br> * The {@link #receive(Address, byte[], int, int)} method must * be called by subclasses when a unicast or multicast message has been received. * @author Bela Ban * @version $Id: TP.java,v 1.267 2009/10/20 15:04:53 belaban Exp $ */ @MBean(description="Transport protocol") @DeprecatedProperty(names={"bind_to_all_interfaces", "use_incoming_packet_handler", "use_outgoing_packet_handler", "use_concurrent_stack", "prevent_port_reuse", "persistent_ports", "pm_expiry_time", "persistent_ports_file"}) public abstract class TP extends Protocol { private static final byte LIST=1; // we have a list of messages rather than a single message when set private static final byte MULTICAST=2; // message is a multicast (versus a unicast) message when set private static final byte OOB=4; // message has OOB flag set (Message.OOB) private static NumberFormat f; private static final int INITIAL_BUFSIZE=4095; static { f=NumberFormat.getNumberInstance(); f.setGroupingUsed(false); f.setMaximumFractionDigits(2); } protected ExposedByteArrayOutputStream out_stream=null; protected ExposedDataOutputStream dos=null; protected final Lock out_stream_lock=new ReentrantLock(); @ManagedAttribute @Property(name="bind_addr", description="The bind address which should be used by this transport", defaultValueIPv4=Global.NON_LOOPBACK_ADDRESS, defaultValueIPv6=Global.NON_LOOPBACK_ADDRESS, systemProperty={Global.BIND_ADDR, Global.BIND_ADDR_OLD}) protected InetAddress bind_addr=null; @Property(name="bind_interface", converter=PropertyConverters.BindInterface.class, description="The interface (NIC) which should be used by this transport", dependsUpon="bind_addr") protected String bind_interface_str=null; @Property(description="Ignores all bind address parameters and let's the OS return the local host address. Default is false") protected boolean use_local_host=false; @ManagedAttribute @Property(description=" If true, the transport should use all available interfaces to receive multicast messages. Default is false") protected boolean receive_on_all_interfaces=false; /** * List<NetworkInterface> of interfaces to receive multicasts on. The multicast receive socket will listen * on all of these interfaces. This is a comma-separated list of IP addresses or interface names. E.g. * "192.168.5.1,eth1,127.0.0.1". Duplicates are discarded; we only bind to * an interface once. If this property is set, it overrides receive_on_all_interfaces. */ @ManagedAttribute @Property(converter=PropertyConverters.NetworkInterfaceList.class, description="Comma delimited list of interfaces (IP addresses or interface names) to receive multicasts on") protected List<NetworkInterface> receive_interfaces=null; /** The port to which the transport binds. 0 means to bind to any (ephemeral) port */ @Property(name="start_port", deprecatedMessage="start_port is deprecated; use bind_port instead", description="The port to which the transport binds. Default of 0 binds to any (ephemeral) port") protected int bind_port=0; @Property(name="end_port", deprecatedMessage="end_port is deprecated; use port_range instead") protected int port_range=5; // 27-6-2003 bgooren, Only try one port by default /** * If true, messages sent to self are treated specially: unicast messages are looped back immediately, * multicast messages get a local copy first and - when the real copy arrives - it will be discarded. Useful for * Window media (non)sense */ @ManagedAttribute(description="", writable=true) @Property(description="Messages to self are looped back immediately if true. Default is false") protected boolean loopback=false; /** * Discard packets with a different version. Usually minor version differences are okay. Setting this property * to true means that we expect the exact same version on all incoming packets */ @ManagedAttribute(description="Discard packets with a different version", writable=true) @Property(description="Discard packets with a different version if true. Default is false") protected boolean discard_incompatible_packets=false; @Property(description="Thread naming pattern for threads in this channel. Default is cl") protected String thread_naming_pattern="cl"; @Property(name="oob_thread_pool.enabled",description="Switch for enabling thread pool for OOB messages. Default true") protected boolean oob_thread_pool_enabled=true; @ManagedAttribute(description="Minimum thread pool size for OOB messages. Default is 2") @Property(name="oob_thread_pool.min_threads",description="Minimum thread pool size for OOB messages. Default is 2") protected int oob_thread_pool_min_threads=2; @ManagedAttribute(description="Maximum thread pool size for OOB messages. Default is 10") @Property(name="oob_thread_pool.max_threads",description="Maximum thread pool size for OOB messages. Default is 10") protected int oob_thread_pool_max_threads=10; @ManagedAttribute(description="Timeout in milliseconds to remove idle thread from OOB pool. Default is 30000") @Property(name="oob_thread_pool.keep_alive_time",description="Timeout in milliseconds to remove idle thread from OOB pool. Default is 30000") protected long oob_thread_pool_keep_alive_time=30000; @ManagedAttribute(description="Use queue to enqueue incoming OOB messages. Default is true") @Property(name="oob_thread_pool.queue_enabled", description="Use queue to enqueue incoming OOB messages. Default is true") protected boolean oob_thread_pool_queue_enabled=true; @ManagedAttribute(description="Maximum queue size for incoming OOB messages. Default is 500") @Property(name="oob_thread_pool.queue_max_size",description="Maximum queue size for incoming OOB messages. Default is 500") protected int oob_thread_pool_queue_max_size=500; @ManagedAttribute @Property(name="oob_thread_pool.rejection_policy", description="Thread rejection policy. Possible values are Abort, Discard, DiscardOldest and Run. Default is Run") String oob_thread_pool_rejection_policy="Run"; @ManagedAttribute(description="Minimum thread pool size for regular messages. Default is 2") @Property(name="thread_pool.min_threads",description="Minimum thread pool size for regular messages. Default is 2") protected int thread_pool_min_threads=2; @ManagedAttribute(description="Maximum thread pool size for regular messages. Default is 10") @Property(name="thread_pool.max_threads",description="Maximum thread pool size for regular messages. Default is 10") protected int thread_pool_max_threads=10; @ManagedAttribute(description="Timeout in milliseconds to remove idle thread from regular pool. Default is 30000") @Property(name="thread_pool.keep_alive_time",description="Timeout in milliseconds to remove idle thread from regular pool. Default is 30000") protected long thread_pool_keep_alive_time=30000; @ManagedAttribute(description="Switch for enabling thread pool for regular messages. Default true") @Property(name="thread_pool.enabled",description="Switch for enabling thread pool for regular messages. Default true") protected boolean thread_pool_enabled=true; @ManagedAttribute(description="Use queue to enqueue incoming regular messages") @Property(name="thread_pool.queue_enabled", description="Use queue to enqueue incoming regular messages. Default is true") protected boolean thread_pool_queue_enabled=true; @ManagedAttribute(description="Maximum queue size for incoming OOB messages") @Property(name="thread_pool.queue_max_size", description="Maximum queue size for incoming OOB messages. Default is 500") protected int thread_pool_queue_max_size=500; @ManagedAttribute @Property(name="thread_pool.rejection_policy", description="Thread rejection policy. Possible values are Abort, Discard, DiscardOldest and Run Default is Run") protected String thread_pool_rejection_policy="Run"; @ManagedAttribute(description="Number of threads to be used by the timer thread pool") @Property(name="timer.num_threads",description="Number of threads to be used by the timer thread pool. Default is 4") protected int num_timer_threads=4; @ManagedAttribute(description="Enable bundling of smaller messages into bigger ones", writable=true) @Property(description="Enable bundling of smaller messages into bigger ones. Default is true") protected boolean enable_bundling=true; /** Enable bundling for unicast messages. Ignored if enable_bundling is off */ @Property(description="Enable bundling of smaller messages into bigger ones for unicast messages. Default is false") protected boolean enable_unicast_bundling=false; @Property(description="Switch to enable diagnostic probing. Default is true") protected boolean enable_diagnostics=true; @Property(description="Address for diagnostic probing. Default is 224.0.75.75", defaultValueIPv4="224.0.75.75",defaultValueIPv6="ff0e::0:75:75") protected InetAddress diagnostics_addr=null; @Property(description="Port for diagnostic probing. Default is 7500") protected int diagnostics_port=7500; @Property(description="If assigned enable this transport to be a singleton (shared) transport") protected String singleton_name=null; /** * Maximum number of bytes for messages to be queued until they are sent. * This value needs to be smaller than the largest datagram packet size in case of UDP */ protected int max_bundle_size=64000; /** * Max number of milliseconds until queued messages are sent. Messages are sent when max_bundle_size * or max_bundle_timeout has been exceeded (whichever occurs faster) */ protected long max_bundle_timeout=20; @ManagedAttribute protected long num_msgs_sent=0; @ManagedAttribute protected long num_msgs_received=0; @ManagedAttribute protected long num_bytes_sent=0; @ManagedAttribute protected long num_bytes_received=0; /** The name of the group to which this member is connected. With a shared transport, the channel name is * in TP.ProtocolAdapter (cluster_name), and this field is not used */ @ManagedAttribute protected String channel_name=null; /** whether or not warnings about messages from different groups are logged - private flag, not for common use */ @ManagedAttribute(writable=true, description="whether or not warnings about messages from different groups are logged") private boolean log_discard_msgs=true; @ManagedAttribute protected long num_oob_msgs_received=0; @ManagedAttribute protected long num_incoming_msgs_received=0; /** The address (host and port) of this member. Null by default when a shared transport is used */ protected Address local_addr=null; /** The members of this group (updated when a member joins or leaves). With a shared transport, * members contains *all* members from all channels sitting on the shared transport */ protected final Set<Address> members=new CopyOnWriteArraySet<Address>(); protected final ExposedByteArrayInputStream in_stream=new ExposedByteArrayInputStream(new byte[] { '0' }); protected final DataInputStream dis=new DataInputStream(in_stream); protected ThreadGroup pool_thread_group=new ThreadGroup(Util.getGlobalThreadGroup(), "Thread Pools"); /** Keeps track of connects and disconnects, in order to start and stop threads */ protected int connect_count=0; protected final ReentrantLock connectLock = new ReentrantLock(); /* Set to true if we are using IPv4 IP addresses, false otherwise */ protected boolean assumeIPv4 = false ; protected Executor oob_thread_pool; /** Factory which is used by oob_thread_pool */ protected ThreadFactory oob_thread_factory=null; /** Used if oob_thread_pool is a ThreadPoolExecutor and oob_thread_pool_queue_enabled is true */ protected BlockingQueue<Runnable> oob_thread_pool_queue=null; /** The thread pool which handles unmarshalling, version checks and dispatching of regular messages */ protected Executor thread_pool; /** Factory which is used by oob_thread_pool */ protected ThreadFactory default_thread_factory=null; /** Used if thread_pool is a ThreadPoolExecutor and thread_pool_queue_enabled is true */ protected BlockingQueue<Runnable> thread_pool_queue=null; protected TimeScheduler timer=null; protected ThreadFactory timer_thread_factory; protected ThreadFactory global_thread_factory=null; private Bundler bundler=null; private DiagnosticsHandler diag_handler=null; private final List<ProbeHandler> preregistered_probe_handlers=new LinkedList<ProbeHandler>(); /** * If singleton_name is enabled, this map is used to de-multiplex incoming messages according to their cluster * names (attached to the message by the transport anyway). The values are the next protocols above the * transports. */ protected final ConcurrentMap<String,Protocol> up_prots=new ConcurrentHashMap<String,Protocol>(); /** The header including the cluster name, sent with each message. Not used with a shared transport (instead * TP.ProtocolAdapter attaches the header to the message */ protected TpHeader header; /** * Cache which maintains mappings between logical and physical addresses. When sending a message to a logical * address, we look up the physical address from logical_addr_cache and send the message to the physical address * <br/> * The keys are logical addresses, the values physical addresses */ protected final LazyRemovalCache<Address,PhysicalAddress> logical_addr_cache=new LazyRemovalCache<Address,PhysicalAddress>(20,120000); private static final LazyRemovalCache.Printable<Address,PhysicalAddress> print_function=new LazyRemovalCache.Printable<Address,PhysicalAddress>() { public java.lang.String print(final Address logical_addr, final PhysicalAddress physical_addr) { StringBuilder sb=new StringBuilder(); String tmp_logical_name=UUID.get(logical_addr); if(tmp_logical_name != null) sb.append(tmp_logical_name).append(": "); sb.append(((UUID)logical_addr).toStringLong()).append(": ").append(physical_addr).append("\n"); return sb.toString(); } }; /** Cache keeping track of WHO_HAS requests for physical addresses (given a logical address) and expiring * them after 5000ms */ protected AgeOutCache<Address> who_has_cache=null; /** * Creates the TP protocol, and initializes the state variables, does * however not start any sockets or threads. */ protected TP() { } /** * debug only */ public String toString() { if(!isSingleton()) return local_addr != null? name + "(local address: " + local_addr + ')' : name; else return name + " (singleton=" + singleton_name + ")"; } public void resetStats() { num_msgs_sent=num_msgs_received=num_bytes_sent=num_bytes_received=0; num_oob_msgs_received=num_incoming_msgs_received=0; } public void registerProbeHandler(ProbeHandler handler) { if(diag_handler != null) diag_handler.registerProbeHandler(handler); else preregistered_probe_handlers.add(handler); } public void unregisterProbeHandler(ProbeHandler handler) { if(diag_handler != null) diag_handler.unregisterProbeHandler(handler); } public void setThreadPoolQueueEnabled(boolean flag) {thread_pool_queue_enabled=flag;} public Executor getDefaultThreadPool() { return thread_pool; } public void setDefaultThreadPool(Executor thread_pool) { if(this.thread_pool != null) shutdownThreadPool(this.thread_pool); this.thread_pool=thread_pool; } public ThreadFactory getDefaultThreadPoolThreadFactory() { return default_thread_factory; } public void setDefaultThreadPoolThreadFactory(ThreadFactory factory) { default_thread_factory=factory; if(thread_pool instanceof ThreadPoolExecutor) ((ThreadPoolExecutor)thread_pool).setThreadFactory(factory); } public Executor getOOBThreadPool() { return oob_thread_pool; } public void setOOBThreadPool(Executor oob_thread_pool) { if(this.oob_thread_pool != null) { shutdownThreadPool(this.oob_thread_pool); } this.oob_thread_pool=oob_thread_pool; } public ThreadFactory getOOBThreadPoolThreadFactory() { return oob_thread_factory; } public void setOOBThreadPoolThreadFactory(ThreadFactory factory) { oob_thread_factory=factory; if(oob_thread_pool instanceof ThreadPoolExecutor) ((ThreadPoolExecutor)oob_thread_pool).setThreadFactory(factory); } public ThreadFactory getTimerThreadFactory() { return timer_thread_factory; } public void setTimerThreadFactory(ThreadFactory factory) { timer_thread_factory=factory; timer.setThreadFactory(factory); } public TimeScheduler getTimer() {return timer;} public ThreadFactory getThreadFactory() { return global_thread_factory; } public void setThreadFactory(ThreadFactory factory) { global_thread_factory=factory; } /** * Names the current thread. Valid values are "pcl": * p: include the previous (original) name, e.g. "Incoming thread-1", "UDP ucast receiver" * c: include the cluster name, e.g. "MyCluster" * l: include the local address of the current member, e.g. "192.168.5.1:5678" */ public String getThreadNamingPattern() {return thread_naming_pattern;} public long getNumMessagesSent() {return num_msgs_sent;} public long getNumMessagesReceived() {return num_msgs_received;} public long getNumBytesSent() {return num_bytes_sent;} public long getNumBytesReceived() {return num_bytes_received;} public String getBindAddress() {return bind_addr != null? bind_addr.toString() : "null";} public void setBindAddress(String bind_addr) throws UnknownHostException { this.bind_addr=InetAddress.getByName(bind_addr); } public InetAddress getBindAddressAsInetAddress() {return bind_addr;} public int getBindPort() {return bind_port;} public void setBindPort(int port) {this.bind_port=port;} /** @deprecated Use {@link #isReceiveOnAllInterfaces()} instead */ public boolean getBindToAllInterfaces() {return receive_on_all_interfaces;} public void setBindToAllInterfaces(boolean flag) {this.receive_on_all_interfaces=flag;} public boolean isReceiveOnAllInterfaces() {return receive_on_all_interfaces;} public List<NetworkInterface> getReceiveInterfaces() {return receive_interfaces;} /** @deprecated This property was removed in 2.7*/ public static boolean isSendOnAllInterfaces() {return false;} /** @deprecated This property was removed in 2.7*/ public static List<NetworkInterface> getSendInterfaces() {return null;} public boolean isDiscardIncompatiblePackets() {return discard_incompatible_packets;} public void setDiscardIncompatiblePackets(boolean flag) {discard_incompatible_packets=flag;} public boolean isEnableBundling() {return enable_bundling;} public void setEnableBundling(boolean flag) {enable_bundling=flag;} public boolean isEnableUnicastBundling() {return enable_unicast_bundling;} public void setEnableUnicastBundling(boolean enable_unicast_bundling) {this.enable_unicast_bundling=enable_unicast_bundling;} public void setPortRange(int range) {this.port_range=range;} public int getPortRange() {return port_range ;} /** @deprecated the concurrent stack is used by default */ @Deprecated public void setUseConcurrentStack(boolean flag) {} @ManagedAttribute public boolean isOOBThreadPoolEnabled() { return oob_thread_pool_enabled; } @ManagedAttribute public boolean isDefaulThreadPoolEnabled() { return thread_pool_enabled; } @ManagedAttribute(description="Maximum number of bytes for messages to be queued until they are sent") public int getMaxBundleSize() {return max_bundle_size;} @ManagedAttribute(description="Maximum number of bytes for messages to be queued until they are sent",writable=true) @Property(name="max_bundle_size") public void setMaxBundleSize(int size) { if(size <= 0) { throw new IllegalArgumentException("max_bundle_size (" + size + ") is <= 0"); } max_bundle_size=size; } @ManagedAttribute(description="Max number of milliseconds until queued messages are sent") public long getMaxBundleTimeout() {return max_bundle_timeout;} @ManagedAttribute(description="Max number of milliseconds until queued messages are sent", writable=true) @Property(name="max_bundle_timeout") public void setMaxBundleTimeout(long timeout) { if(timeout <= 0) { throw new IllegalArgumentException("max_bundle_timeout of " + timeout + " is invalid"); } max_bundle_timeout=timeout; } public boolean isLoopback() {return loopback;} public void setLoopback(boolean b) {loopback=b;} /** @deprecated With the concurrent stack being the default, this property is ignored */ public static boolean isUseIncomingPacketHandler() {return false;} public ConcurrentMap<String,Protocol> getUpProtocols() { return up_prots; } @ManagedAttribute public int getOOBMinPoolSize() { return oob_thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)oob_thread_pool).getCorePoolSize() : 0; } @ManagedAttribute public void setOOBMinPoolSize(int size) { if(oob_thread_pool instanceof ThreadPoolExecutor) ((ThreadPoolExecutor)oob_thread_pool).setCorePoolSize(size); } @ManagedAttribute public int getOOBMaxPoolSize() { return oob_thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)oob_thread_pool).getMaximumPoolSize() : 0; } @ManagedAttribute public void setOOBMaxPoolSize(int size) { if(oob_thread_pool instanceof ThreadPoolExecutor) ((ThreadPoolExecutor)oob_thread_pool).setMaximumPoolSize(size); } @ManagedAttribute public int getOOBPoolSize() { return oob_thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)oob_thread_pool).getPoolSize() : 0; } @ManagedAttribute public long getOOBKeepAliveTime() { return oob_thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)oob_thread_pool).getKeepAliveTime(TimeUnit.MILLISECONDS) : 0; } @ManagedAttribute public void setOOBKeepAliveTime(long time) { if(oob_thread_pool instanceof ThreadPoolExecutor) ((ThreadPoolExecutor)oob_thread_pool).setKeepAliveTime(time, TimeUnit.MILLISECONDS); } public long getOOBMessages() { return num_oob_msgs_received; } @ManagedAttribute public int getOOBQueueSize() { return oob_thread_pool_queue.size(); } public int getOOBMaxQueueSize() { return oob_thread_pool_queue_max_size; } @ManagedAttribute public int getOOBActiveThreads() { return oob_thread_pool instanceof ThreadPoolExecutor ? ((ThreadPoolExecutor)oob_thread_pool).getActiveCount() : 0; } @ManagedAttribute public int getIncomingMinPoolSize() { return thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)thread_pool).getCorePoolSize() : 0; } @ManagedAttribute public void setIncomingMinPoolSize(int size) { if(thread_pool instanceof ThreadPoolExecutor) ((ThreadPoolExecutor)thread_pool).setCorePoolSize(size); } @ManagedAttribute public int getIncomingMaxPoolSize() { return thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)thread_pool).getMaximumPoolSize() : 0; } @ManagedAttribute public void setIncomingMaxPoolSize(int size) { if(thread_pool instanceof ThreadPoolExecutor) ((ThreadPoolExecutor)thread_pool).setMaximumPoolSize(size); } @ManagedAttribute public int getIncomingPoolSize() { return thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)thread_pool).getPoolSize() : 0; } @ManagedAttribute public long getIncomingKeepAliveTime() { return thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)thread_pool).getKeepAliveTime(TimeUnit.MILLISECONDS) : 0; } @ManagedAttribute public void setIncomingKeepAliveTime(long time) { if(thread_pool instanceof ThreadPoolExecutor) ((ThreadPoolExecutor)thread_pool).setKeepAliveTime(time, TimeUnit.MILLISECONDS); } public long getIncomingMessages() { return num_incoming_msgs_received; } @ManagedAttribute public int getIncomingQueueSize() { return thread_pool_queue.size(); } public int getIncomingMaxQueueSize() { return thread_pool_queue_max_size; } @ManagedAttribute public int getIncomingActiveThreads() { return thread_pool instanceof ThreadPoolExecutor ? ((ThreadPoolExecutor)thread_pool).getActiveCount() : 0; } public void setLogDiscardMessages(boolean flag) { log_discard_msgs=flag; } public boolean getLogDiscardMessages() { return log_discard_msgs; } @ManagedOperation(description="Dumps the contents of the logical address cache") public String printLogicalAddressCache() { return logical_addr_cache.printCache(print_function); } /** * Send to all members in the group. UDP would use an IP multicast message, whereas TCP would send N * messages, one for each member * @param data The data to be sent. This is not a copy, so don't modify it * @param offset * @param length * @throws Exception */ public abstract void sendMulticast(byte[] data, int offset, int length) throws Exception; /** * Send a unicast to 1 member. Note that the destination address is a *physical*, not a logical address * @param dest Must be a non-null unicast address * @param data The data to be sent. This is not a copy, so don't modify it * @param offset * @param length * @throws Exception */ public abstract void sendUnicast(PhysicalAddress dest, byte[] data, int offset, int length) throws Exception; public abstract String getInfo(); public void init() throws Exception { super.init(); // Create the default thread factory global_thread_factory=new DefaultThreadFactory(Util.getGlobalThreadGroup(), "", false); // Create the timer and the associated thread factory - depends on singleton_name // timer_thread_factory=new DefaultThreadFactory(Util.getGlobalThreadGroup(), "Timer", true, true); timer_thread_factory=new LazyThreadFactory(Util.getGlobalThreadGroup(), "Timer", true, true); if(isSingleton()) { timer_thread_factory.setIncludeClusterName(false); } default_thread_factory=new DefaultThreadFactory(pool_thread_group, "Incoming", false, true); oob_thread_factory=new DefaultThreadFactory(pool_thread_group, "OOB", false, true); // local_addr is null when shared transport, channel_name is not used setInAllThreadFactories(channel_name, local_addr, thread_naming_pattern); timer=new TimeScheduler(timer_thread_factory, num_timer_threads); who_has_cache=new AgeOutCache<Address>(timer, 5000L); verifyRejectionPolicy(oob_thread_pool_rejection_policy); verifyRejectionPolicy(thread_pool_rejection_policy); out_stream=new ExposedByteArrayOutputStream(INITIAL_BUFSIZE); dos=new ExposedDataOutputStream(out_stream); if(oob_thread_pool_enabled) { if(oob_thread_pool_queue_enabled) oob_thread_pool_queue=new LinkedBlockingQueue<Runnable>(oob_thread_pool_queue_max_size); else oob_thread_pool_queue=new SynchronousQueue<Runnable>(); oob_thread_pool=createThreadPool(oob_thread_pool_min_threads, oob_thread_pool_max_threads, oob_thread_pool_keep_alive_time, oob_thread_pool_rejection_policy, oob_thread_pool_queue, oob_thread_factory); } else { // otherwise use the caller's thread to unmarshal the byte buffer into a message oob_thread_pool=new DirectExecutor(); } if(thread_pool_enabled) { if(thread_pool_queue_enabled) thread_pool_queue=new LinkedBlockingQueue<Runnable>(thread_pool_queue_max_size); else thread_pool_queue=new SynchronousQueue<Runnable>(); thread_pool=createThreadPool(thread_pool_min_threads, thread_pool_max_threads, thread_pool_keep_alive_time, thread_pool_rejection_policy, thread_pool_queue, default_thread_factory); } else { // otherwise use the caller's thread to unmarshal the byte buffer into a message thread_pool=new DirectExecutor(); } if(bind_addr != null) { Map<String, Object> m=new HashMap<String, Object>(1); m.put("bind_addr", bind_addr); up(new Event(Event.CONFIG, m)); } } public void destroy() { super.destroy(); if(timer != null) { try { timer.stop(); } catch(InterruptedException e) { log.error("failed stopping the timer", e); } } // 3. Stop the thread pools if(oob_thread_pool instanceof ThreadPoolExecutor) { shutdownThreadPool(oob_thread_pool); } if(thread_pool instanceof ThreadPoolExecutor) { shutdownThreadPool(thread_pool); } } /** * Creates the unicast and multicast sockets and starts the unicast and multicast receiver threads */ public void start() throws Exception { fetchLocalAddresses(); if(timer == null) throw new Exception("timer is null"); if(enable_diagnostics) { diag_handler=new DiagnosticsHandler(); diag_handler.start(); for(ProbeHandler handler: preregistered_probe_handlers) diag_handler.registerProbeHandler(handler); preregistered_probe_handlers.clear(); } if(enable_bundling) { bundler=new Bundler(); } // local_addr is null when shared transport setInAllThreadFactories(channel_name, local_addr, thread_naming_pattern); } public void stop() { if(diag_handler != null) { diag_handler.stop(); diag_handler=null; } preregistered_probe_handlers.clear(); } protected void handleConnect() throws Exception { connect_count++; } protected void handleDisconnect() { connect_count=Math.max(0, connect_count -1); } public String getSingletonName() { return singleton_name; } public boolean isSingleton(){ return singleton_name != null && singleton_name.length() >0; } /** * handle the UP event. * @param evt - the event being send from the stack */ public Object up(Event evt) { if(isSingleton()) { passToAllUpProtocols(evt); return null; } else return up_prot.up(evt); } /** * Caller by the layer above this layer. Usually we just put this Message * into the send queue and let one or more worker threads handle it. A worker thread * then removes the Message from the send queue, performs a conversion and adds the * modified Message to the send queue of the layer below it, by calling down()). */ public Object down(Event evt) { if(evt.getType() != Event.MSG) { // unless it is a message handle it and respond return handleDownEvent(evt); } Message msg=(Message)evt.getArg(); if(header != null) { // added patch by Roland Kurmann (March 20 2003) // msg.putHeader(name, new TpHeader(channel_name)); msg.putHeaderIfAbsent(name, header); } if(!isSingleton()) setSourceAddress(msg); // very important !! listToBuffer() will fail with a null src address !! if(log.isTraceEnabled()) { log.trace("sending msg to " + msg.getDest() + ", src=" + msg.getSrc() + ", headers are " + msg.printHeaders()); } // Don't send if destination is local address. Instead, switch dst and src and put in up_queue. // If multicast message, loopback a copy directly to us (but still multicast). Once we receive this, // we will discard our own multicast message Address dest=msg.getDest(); if(dest instanceof PhysicalAddress) { // We can modify the message because it won't get retransmitted. The only time we have a physical address // as dest is when TCPPING sends the initial discovery requests to initial_hosts: this is below UNICAST, // so no retransmission msg.setDest(null); } boolean multicast=dest == null || dest.isMulticastAddress(); if(loopback && (multicast || dest.equals(msg.getSrc()))) { // we *have* to make a copy, or else up_prot.up() might remove headers from msg which will then *not* // be available for marshalling further down (when sending the message) final Message copy=msg.copy(); if(log.isTraceEnabled()) log.trace(new StringBuilder("looping back message ").append(copy)); // up_prot.up(new Event(Event.MSG, copy)); Executor pool=msg.isFlagSet(Message.OOB)? oob_thread_pool : thread_pool; pool.execute(new Runnable() { public void run() { passMessageUp(copy, false); } }); if(!multicast) return null; } try { send(msg, dest, multicast); } catch(InterruptedException interruptedEx) { Thread.currentThread().interrupt(); // let someone else handle the interrupt } catch(Throwable e) { if(log.isErrorEnabled()) { String dst=msg.getDest() == null? "null" : msg.getDest().toString(); log.error("failed sending message to " + dst + " (" + msg.size() + " bytes)", e); } } return null; } /** * If the sender is null, set our own address. We cannot just go ahead and set the address * anyway, as we might be sending a message on behalf of someone else ! E.g. in case of * retransmission, when the original sender has crashed, or in a FLUSH protocol when we * have to return all unstable messages with the FLUSH_OK response. */ private void setSourceAddress(Message msg) { if(msg.getSrc() == null && local_addr != null) // should already be set by TP.ProtocolAdapter in shared transport case ! msg.setSrc(local_addr); } private void passMessageUp(Message msg, boolean perform_cluster_name_matching) { TpHeader hdr=(TpHeader)msg.getHeader(name); // replaced removeHeader() with getHeader() if(hdr == null) { if(log.isErrorEnabled()) log.error(new StringBuilder("message does not have a transport header, msg is ").append(msg). append(", headers are ").append(msg.printHeaders()).append(", will be discarded").toString()); return; } if(log.isTraceEnabled()) log.trace(new StringBuilder("message is ").append(msg).append(", headers are ").append(msg.printHeaders())); String ch_name=hdr.channel_name; if(isSingleton()) { Protocol tmp_prot=up_prots.get(ch_name); if(tmp_prot != null) { tmp_prot.up(new Event(Event.MSG, msg)); } } else { // Discard if message's cluster name is not the same as our cluster name if(perform_cluster_name_matching && channel_name != null && !channel_name.equals(ch_name)) { if(log.isWarnEnabled() && log_discard_msgs) log.warn(new StringBuilder("discarded message from different cluster \"").append(ch_name). append("\" (our cluster is \"").append(channel_name).append("\"). Sender was ").append(msg.getSrc()).toString()); } else { up_prot.up(new Event(Event.MSG, msg)); } } } /** * Subclasses must call this method when a unicast or multicast message has been received. * Declared final so subclasses cannot override this method. * * @param sender * @param data * @param offset * @param length */ protected void receive(Address sender, byte[] data, int offset, int length) { if(data == null) return; try { // determine whether OOB or not by looking at first byte of 'data' byte oob_flag=data[Global.SHORT_SIZE]; // we need to skip the first 2 bytes (version) if((oob_flag & OOB) == OOB) { num_oob_msgs_received++; dispatchToThreadPool(oob_thread_pool, sender, data, offset, length); } else { num_incoming_msgs_received++; dispatchToThreadPool(thread_pool, sender, data, offset, length); } } catch(Throwable t) { if(log.isErrorEnabled()) log.error(new StringBuilder("failed handling data from ").append(sender).toString(), t); } } private void dispatchToThreadPool(Executor pool, Address sender, byte[] data, int offset, int length) { if(pool instanceof DirectExecutor) { // we don't make a copy of the buffer if we execute on this thread pool.execute(new IncomingPacket(sender, data, offset, length)); } else { byte[] tmp=new byte[length]; System.arraycopy(data, offset, tmp, 0, length); pool.execute(new IncomingPacket(sender, tmp, 0, length)); } } /** Serializes and sends a message. This method is not reentrant */ protected void send(Message msg, Address dest, boolean multicast) throws Exception { // bundle only regular messages; send OOB messages directly if(enable_bundling && !(msg.isFlagSet(Message.OOB) || msg.isFlagSet(Message.DONT_BUNDLE))) { if(!enable_unicast_bundling && !multicast) { ; } else { bundler.send(msg, dest); return; } } out_stream_lock.lock(); try { out_stream.reset(); dos.reset(); writeMessage(msg, dos, multicast); Buffer buf=new Buffer(out_stream.getRawBuffer(), 0, out_stream.size()); doSend(buf, dest, multicast); } finally { out_stream_lock.unlock(); } } protected void doSend(Buffer buf, Address dest, boolean multicast) throws Exception { if(stats) { num_msgs_sent++; num_bytes_sent+=buf.getLength(); } if(multicast) { sendMulticast(buf.getBuf(), buf.getOffset(), buf.getLength()); } else { sendToSingleMember(dest, buf.getBuf(), buf.getOffset(), buf.getLength()); } } protected void sendToSingleMember(Address dest, byte[] buf, int offset, int length) throws Exception { PhysicalAddress physical_dest=dest instanceof PhysicalAddress? (PhysicalAddress)dest : getPhysicalAddressFromCache(dest); if(physical_dest == null) { if(!who_has_cache.contains(dest)) { who_has_cache.add(dest); if(log.isWarnEnabled()) log.warn(local_addr+ ": no physical address for " + dest + ", dropping message"); up(new Event(Event.GET_PHYSICAL_ADDRESS, dest)); } return; } sendUnicast(physical_dest, buf, offset, length); } protected void sendToAllPhysicalAddresses(byte[] buf, int offset, int length) throws Exception { Set<PhysicalAddress> dests=new HashSet<PhysicalAddress>(logical_addr_cache.values()); for(PhysicalAddress dest: dests) { sendUnicast(dest, buf, offset, length); } } /** * This method needs to be synchronized on out_stream when it is called * @param msg * @return * @throws java.io.IOException */ protected static void writeMessage(Message msg, DataOutputStream dos, boolean multicast) throws Exception { byte flags=0; dos.writeShort(Version.version); // write the version if(multicast) flags+=MULTICAST; if(msg.isFlagSet(Message.OOB)) flags+=OOB; dos.writeByte(flags); msg.writeTo(dos); } protected static Message readMessage(DataInputStream instream) throws Exception { Message msg=new Message(false); // don't create headers, readFrom() will do this msg.readFrom(instream); return msg; } private static void writeMessageList(List<Message> msgs, DataOutputStream dos, boolean multicast) throws Exception { byte flags=0; int len=msgs != null? msgs.size() : 0; dos.writeShort(Version.version); flags+=LIST; if(multicast) flags+=MULTICAST; dos.writeByte(flags); dos.writeInt(len); if(msgs != null) { for(Message msg: msgs) { msg.writeTo(dos); } } } private static List<Message> readMessageList(DataInputStream instream) throws Exception { int len; Message msg; len=instream.readInt(); List<Message> list=new ArrayList<Message>(len); for(int i=0; i < len; i++) { msg=new Message(false); // don't create headers, readFrom() will do this msg.readFrom(instream); list.add(msg); } return list; } @SuppressWarnings("unchecked") protected Object handleDownEvent(Event evt) { switch(evt.getType()) { case Event.TMP_VIEW: case Event.VIEW_CHANGE: synchronized(members) { View view=(View)evt.getArg(); members.clear(); if(!isSingleton()) { Vector<Address> tmpvec=view.getMembers(); members.addAll(tmpvec); } else { // add all members from all clusters for(Protocol prot: up_prots.values()) { if(prot instanceof ProtocolAdapter) { ProtocolAdapter ad=(ProtocolAdapter)prot; Set<Address> tmp=ad.getMembers(); members.addAll(tmp); } } } } logical_addr_cache.retainAll(members); UUID.retainAll(members); break; case Event.CONNECT: case Event.CONNECT_WITH_STATE_TRANSFER: case Event.CONNECT_USE_FLUSH: case Event.CONNECT_WITH_STATE_TRANSFER_USE_FLUSH: channel_name=(String)evt.getArg(); header=new TpHeader(channel_name); // local_addr is null when shared transport setInAllThreadFactories(channel_name, local_addr, thread_naming_pattern); setThreadNames(); connectLock.lock(); try { handleConnect(); } catch(Exception e) { throw new RuntimeException(e); } finally { connectLock.unlock(); } return null; case Event.DISCONNECT: unsetThreadNames(); connectLock.lock(); try { handleDisconnect(); } finally { connectLock.unlock(); } break; case Event.GET_PHYSICAL_ADDRESS: return getPhysicalAddressFromCache((UUID)evt.getArg()); case Event.GET_LOGICAL_PHYSICAL_MAPPINGS: return logical_addr_cache.contents(); case Event.SET_PHYSICAL_ADDRESS: Tuple<UUID,PhysicalAddress> tuple=(Tuple<UUID,PhysicalAddress>)evt.getArg(); addPhysicalAddressToCache(tuple.getVal1(), tuple.getVal2()); break; case Event.REMOVE_ADDRESS: removeLogicalAddressFromCache((UUID)evt.getArg()); break; case Event.SET_LOCAL_ADDRESS: if(!isSingleton()) local_addr=(Address)evt.getArg(); registerLocalAddress((Address)evt.getArg()); break; } return null; } /** * Associates the address with the physical address fetched from the cache * @param addr * @return true if registered successfully, otherwise false (e.g. physical addr could not be fetched) */ protected void registerLocalAddress(Address addr) { PhysicalAddress physical_addr=getPhysicalAddress(); if(physical_addr != null && addr != null) addPhysicalAddressToCache(addr, physical_addr); } /** * Grabs the local address (or addresses in the shared transport case) and registers them with the physical address * in the transport's cache */ protected void fetchLocalAddresses() { if(!isSingleton()) { if(local_addr != null) { registerLocalAddress(local_addr); } else { Address addr=(Address)up_prot.up(new Event(Event.GET_LOCAL_ADDRESS)); local_addr=addr; registerLocalAddress(addr); } } else { for(Protocol prot: up_prots.values()) { Address addr=(Address)prot.up(new Event(Event.GET_LOCAL_ADDRESS)); registerLocalAddress(addr); } } } protected void setThreadNames() { if(diag_handler != null) { global_thread_factory.renameThread(DiagnosticsHandler.THREAD_NAME, diag_handler.getThread()); } } protected void unsetThreadNames() { if(diag_handler != null && diag_handler.getThread() != null) diag_handler.getThread().setName(DiagnosticsHandler.THREAD_NAME); } private void setInAllThreadFactories(String cluster_name, Address local_address, String pattern) { ThreadFactory[] factories= {timer_thread_factory, default_thread_factory, oob_thread_factory, global_thread_factory }; boolean is_shared_transport=isSingleton(); for(ThreadFactory factory:factories) { if(pattern != null) { factory.setPattern(pattern); if(is_shared_transport) factory.setIncludeClusterName(false); } if(cluster_name != null && !is_shared_transport) // only set cluster name if we don't have a shared transport factory.setClusterName(cluster_name); if(local_address != null) factory.setAddress(local_address.toString()); } } protected static ExecutorService createThreadPool(int min_threads, int max_threads, long keep_alive_time, String rejection_policy, BlockingQueue<Runnable> queue, final ThreadFactory factory) { ThreadPoolExecutor pool=new ThreadManagerThreadPoolExecutor(min_threads, max_threads, keep_alive_time, TimeUnit.MILLISECONDS, queue); pool.setThreadFactory(factory); //default RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy(); if(rejection_policy != null) { if(rejection_policy.equals("abort")) handler = new ThreadPoolExecutor.AbortPolicy(); else if(rejection_policy.equals("discard")) handler = new ThreadPoolExecutor.DiscardPolicy(); else if(rejection_policy.equals("discardoldest")) handler = new ThreadPoolExecutor.DiscardOldestPolicy(); } pool.setRejectedExecutionHandler(new ShutdownRejectedExecutionHandler(handler)); return pool; } private static void shutdownThreadPool(Executor thread_pool) { if(thread_pool instanceof ExecutorService) { ExecutorService service=(ExecutorService)thread_pool; service.shutdownNow(); try { service.awaitTermination(Global.THREADPOOL_SHUTDOWN_WAIT_TIME, TimeUnit.MILLISECONDS); } catch(InterruptedException e) { } } } private void verifyRejectionPolicy(String str) throws Exception{ if(!(str.equalsIgnoreCase("run") || str.equalsIgnoreCase("abort")|| str.equalsIgnoreCase("discard")|| str.equalsIgnoreCase("discardoldest"))) { log.error("rejection policy of " + str + " is unknown"); throw new Exception("Unknown rejection policy " + str); } } protected void passToAllUpProtocols(Event evt) { for(Protocol prot: up_prots.values()) { try { prot.up(evt); } catch(Exception e) { if(log.isErrorEnabled()) log.error("failed passing up event " + evt, e); } } } protected void addPhysicalAddressToCache(Address logical_addr, PhysicalAddress physical_addr) { if(logical_addr != null && physical_addr != null) logical_addr_cache.add(logical_addr, physical_addr); } protected PhysicalAddress getPhysicalAddressFromCache(Address logical_addr) { return logical_addr != null? logical_addr_cache.get(logical_addr) : null; } protected void removeLogicalAddressFromCache(Address logical_addr) { if(logical_addr != null) logical_addr_cache.remove(logical_addr); } @ManagedOperation public void clearLogicalAddressCache() { logical_addr_cache.clear(true); } protected abstract PhysicalAddress getPhysicalAddress(); class IncomingPacket implements Runnable { final Address sender; final byte[] buf; final int offset, length; IncomingPacket(Address sender, byte[] buf, int offset, int length) { this.sender=sender; this.buf=buf; this.offset=offset; this.length=length; } /** Code copied from handleIncomingPacket */ public void run() { short version; byte flags; ExposedByteArrayInputStream in_stream; DataInputStream dis=null; try { in_stream=new ExposedByteArrayInputStream(buf, offset, length); dis=new DataInputStream(in_stream); try { version=dis.readShort(); } catch(IOException ex) { if(discard_incompatible_packets) return; throw ex; } if(Version.isBinaryCompatible(version) == false) { if(log.isWarnEnabled()) { StringBuilder sb=new StringBuilder(); sb.append("packet from ").append(sender).append(" has different version (").append(Version.print(version)); sb.append(") from ours (").append(Version.printVersion()).append("). "); if(discard_incompatible_packets) sb.append("Packet is discarded"); else sb.append("This may cause problems"); log.warn(sb.toString()); } if(discard_incompatible_packets) return; } flags=dis.readByte(); boolean is_message_list=(flags & LIST) == LIST; boolean multicast=(flags & MULTICAST) == MULTICAST; if(is_message_list) { // used if message bundling is enabled List<Message> msgs=readMessageList(dis); for(Message msg: msgs) { if(msg.isFlagSet(Message.OOB)) { log.warn("bundled message should not be marked as OOB"); } handleMyMessage(msg, multicast); } } else { Message msg=readMessage(dis); handleMyMessage(msg, multicast); } } catch(Throwable t) { if(log.isErrorEnabled()) log.error("failed handling incoming message", t); } finally { Util.close(dis); } } private void handleMyMessage(Message msg, boolean multicast) { if(stats) { num_msgs_received++; num_bytes_received+=msg.getLength(); } if(loopback && multicast && msg.isFlagSet(Message.LOOPBACK)) { return; // drop message that was already looped back and delivered } passMessageUp(msg, true); } } private class Bundler { static final int MIN_NUMBER_OF_BUNDLING_TASKS=2; /** HashMap<Address, List<Message>>. Keys are destinations, values are lists of Messages */ final Map<Address,List<Message>> msgs=new HashMap<Address,List<Message>>(36); @GuardedBy("lock") long count=0; // current number of bytes accumulated int num_msgs=0; @GuardedBy("lock") int num_bundling_tasks=0; long last_bundle_time; final ReentrantLock lock=new ReentrantLock(); final ExposedByteArrayOutputStream bundler_out_stream=new ExposedByteArrayOutputStream(INITIAL_BUFSIZE); final ExposedDataOutputStream bundler_dos=new ExposedDataOutputStream(bundler_out_stream); private void send(Message msg, Address dest) throws Exception { long length=msg.size(); checkLength(length); lock.lock(); try { if(count + length >= max_bundle_size) { if(!msgs.isEmpty()) { sendBundledMessages(msgs); } } addMessage(msg, dest); count+=length; if(num_bundling_tasks < MIN_NUMBER_OF_BUNDLING_TASKS) { num_bundling_tasks++; timer.schedule(new BundlingTimer(), max_bundle_timeout, TimeUnit.MILLISECONDS); } } finally { lock.unlock(); } } /** Run with lock acquired */ private void addMessage(Message msg, Address dest) { // no sync needed, always called with lock held if(msgs.isEmpty()) last_bundle_time=System.currentTimeMillis(); List<Message> tmp=msgs.get(dest); if(tmp == null) { tmp=new LinkedList<Message>(); msgs.put(dest, tmp); } tmp.add(msg); num_msgs++; } /** * Sends all messages from the map, all messages for the same destination are bundled into 1 message. * This method may be called by timer and bundler concurrently * @param msgs */ private void sendBundledMessages(final Map<Address,List<Message>> msgs) { boolean multicast; Buffer buffer; Address dst; if(log.isTraceEnabled()) { long stop=System.currentTimeMillis(); double percentage=100.0 / max_bundle_size * count; StringBuilder sb=new StringBuilder("sending ").append(num_msgs).append(" msgs ("); num_msgs=0; sb.append(count).append(" bytes (" + f.format(percentage) + "% of max_bundle_size)"); if(last_bundle_time > 0) { sb.append(", collected in ").append(stop-last_bundle_time).append("ms) "); } sb.append(" to ").append(msgs.size()).append(" destination(s)"); if(msgs.size() > 1) sb.append(" (dests=").append(msgs.keySet()).append(")"); log.trace(sb); } for(Map.Entry<Address,List<Message>> entry: msgs.entrySet()) { List<Message> list=entry.getValue(); if(list.isEmpty()) continue; dst=entry.getKey(); multicast=dst == null || dst.isMulticastAddress(); try { bundler_out_stream.reset(); bundler_dos.reset(); writeMessageList(list, bundler_dos, multicast); // flushes output stream when done buffer=new Buffer(bundler_out_stream.getRawBuffer(), 0, bundler_out_stream.size()); doSend(buffer, dst, multicast); } catch(Throwable e) { if(log.isErrorEnabled()) log.error("exception sending msg: " + e.toString(), e); } } msgs.clear(); count=0; } private void checkLength(long len) throws Exception { if(len > max_bundle_size) throw new Exception("message size (" + len + ") is greater than max bundling size (" + max_bundle_size + "). Set the fragmentation/bundle size in FRAG and TP correctly"); } private class BundlingTimer implements Runnable { public void run() { lock.lock(); try { if(!msgs.isEmpty()) { sendBundledMessages(msgs); } } finally { num_bundling_tasks lock.unlock(); } } } } public interface ProbeHandler { /** * Handles a probe. For each key that is handled, the key and its result should be in the returned map. * @param keys * @return Map<String,String>. A map of keys and values. A null return value is permissible. */ Map<String,String> handleProbe(String... keys); /** Returns a list of supported keys */ String[] supportedKeys(); } // /** // * Maps UUIDs to physical addresses // */ // public interface AddressMapper { // /** // * Given a UUID, pick one physical address from a list. If the UUID is null, the message needs to be sent to // * the entire cluster. In UDP, for example, we would pick a multicast address // * @param uuid The UUID. Null for a cluster wide destination // * @param physical_addrs A list of physical addresses // * @return an address from the list // */ // Address pick(UUID uuid, List<Address> physical_addrs); private class DiagnosticsHandler implements Runnable { public static final String THREAD_NAME = "DiagnosticsHandler"; private Thread thread=null; private MulticastSocket diag_sock=null; private final Set<ProbeHandler> handlers=new HashSet<ProbeHandler>(); DiagnosticsHandler() { } Thread getThread(){ return thread; } void registerProbeHandler(ProbeHandler handler) { if(handler != null) handlers.add(handler); } void unregisterProbeHandler(ProbeHandler handler) { if(handler != null) handlers.remove(handler); } void start() throws IOException { registerProbeHandler(new ProbeHandler() { public Map<String, String> handleProbe(String... keys) { Map<String,String> retval=new HashMap<String,String>(2); for(String key: keys) { if(key.equals("dump")) { retval.put("dump", Util.dumpThreads()); continue; } if(key.equals("uuids")) { retval.put("uuids", printLogicalAddressCache()); if(!isSingleton() && !retval.containsKey("local_addr")) retval.put("local_addr", local_addr != null? local_addr.toString() : null); continue; } if(key.equals("keys")) { StringBuilder sb=new StringBuilder(); for(ProbeHandler handler: handlers) { String[] tmp=handler.supportedKeys(); if(tmp != null && tmp.length > 0) { for(String s: tmp) sb.append(s).append(" "); } } retval.put("keys", sb.toString()); } if(key.equals("info")) { if(singleton_name != null && singleton_name.length() > 0) retval.put("singleton_name", singleton_name); } } return retval; } public String[] supportedKeys() { return new String[]{"dump", "keys", "uuids", "info"}; } }); diag_sock=new MulticastSocket(diagnostics_port); // diag_sock=Util.createMulticastSocket(null, diagnostics_port, log); List<NetworkInterface> interfaces=Util.getAllAvailableInterfaces(); bindToInterfaces(interfaces, diag_sock); if(thread == null || !thread.isAlive()) { thread=global_thread_factory.newThread(this, THREAD_NAME); thread.setDaemon(true); thread.start(); } } void stop() { if(diag_sock != null) diag_sock.close(); handlers.clear(); if(thread != null){ try{ thread.join(Global.THREAD_SHUTDOWN_WAIT_TIME); } catch(InterruptedException e){ Thread.currentThread().interrupt(); // set interrupt flag } } } public void run() { byte[] buf=new byte[1500]; // requests are small (responses might be bigger) DatagramPacket packet; while(!diag_sock.isClosed() && Thread.currentThread().equals(thread)) { packet=new DatagramPacket(buf, 0, buf.length); try { diag_sock.receive(packet); handleDiagnosticProbe(packet.getSocketAddress(), diag_sock, new String(packet.getData(), packet.getOffset(), packet.getLength())); } catch(IOException socket_ex) { } catch(Throwable e) { if(log.isErrorEnabled()) log.error("failure handling diagnostics request", e); } } } private void handleDiagnosticProbe(SocketAddress sender, DatagramSocket sock, String request) { StringTokenizer tok=new StringTokenizer(request); List<String> list=new ArrayList<String>(10); while(tok.hasMoreTokens()) { String req=tok.nextToken().trim(); if(req.length() > 0) list.add(req); } String[] tokens=new String[list.size()]; for(int i=0; i < list.size(); i++) tokens[i]=list.get(i); for(ProbeHandler handler: handlers) { Map<String, String> map=handler.handleProbe(tokens); if(map == null || map.isEmpty()) continue; if(!map.containsKey("cluster")) map.put("cluster", channel_name != null? channel_name : "n/a"); StringBuilder info=new StringBuilder(); for(Map.Entry<String,String> entry: map.entrySet()) { info.append(entry.getKey()).append("=").append(entry.getValue()).append("\r\n"); } byte[] diag_rsp=info.toString().getBytes(); if(log.isDebugEnabled()) log.debug("sending diag response to " + sender); try { sendResponse(sock, sender, diag_rsp); } catch(Throwable t) { if(log.isErrorEnabled()) log.error("failed sending diag rsp to " + sender, t); } } } private void sendResponse(DatagramSocket sock, SocketAddress sender, byte[] buf) throws IOException { DatagramPacket p=new DatagramPacket(buf, 0, buf.length, sender); sock.send(p); } private void bindToInterfaces(List<NetworkInterface> interfaces, MulticastSocket s) { SocketAddress group_addr=new InetSocketAddress(diagnostics_addr, diagnostics_port); for(Iterator<NetworkInterface> it=interfaces.iterator(); it.hasNext();) { NetworkInterface i=it.next(); try { if (i.getInetAddresses().hasMoreElements()) { // fix for VM crash - suggested by JJalenak@netopia.com s.joinGroup(group_addr, i); if(log.isTraceEnabled()) log.trace("joined " + group_addr + " on " + i.getName()); } } catch(IOException e) { log.warn("failed to join " + group_addr + " on " + i.getName() + ": " + e); } } } } /** * Used when the transport is shared (singleton_name is not null). Maintains the cluster name, local address and * view */ public static class ProtocolAdapter extends Protocol implements ProbeHandler { String cluster_name; final String transport_name; TpHeader header; final Set<Address> members=new CopyOnWriteArraySet<Address>(); final ThreadFactory factory; Address local_addr; static final ThreadLocal<ProtocolAdapter> thread_local=new ThreadLocal<ProtocolAdapter>(); public ProtocolAdapter(String cluster_name, Address local_addr, String transport_name, Protocol up, Protocol down, String pattern) { this.cluster_name=cluster_name; this.local_addr=local_addr; this.transport_name=transport_name; this.up_prot=up; this.down_prot=down; this.header=new TpHeader(cluster_name); this.factory=new DefaultThreadFactory(Util.getGlobalThreadGroup(), "", false); factory.setPattern(pattern); if(local_addr != null) factory.setAddress(local_addr.toString()); if(cluster_name != null) factory.setClusterName(cluster_name); } @ManagedAttribute(description="Name of the cluster to which this adapter proxies") public String getClusterName() { return cluster_name; } public Address getAddress() { return local_addr; } @ManagedAttribute(name="Address", description="local address") public String getAddressAsString() { return local_addr != null? local_addr.toString() : null; } @ManagedAttribute(name="AddressUUID", description="local address") public String getAddressAsUUID() { return (local_addr instanceof UUID)? ((UUID)local_addr).toStringLong() : null; } @ManagedAttribute(description="Name of the transport") public String getTransportName() { return transport_name; } public Set<Address> getMembers() { return Collections.unmodifiableSet(members); } public ThreadFactory getThreadFactory() { return factory; } public void start() throws Exception { TP transport=getTransport(); if(transport != null) transport.registerProbeHandler(this); } public void stop() { TP transport=getTransport(); if(transport != null) transport.unregisterProbeHandler(this); } public Object down(Event evt) { switch(evt.getType()) { case Event.MSG: Message msg=(Message)evt.getArg(); msg.putHeader(transport_name, header); if(msg.getSrc() == null) msg.setSrc(local_addr); break; case Event.VIEW_CHANGE: View view=(View)evt.getArg(); Vector<Address> tmp=view.getMembers(); members.clear(); members.addAll(tmp); break; case Event.DISCONNECT: thread_local.set(this); break; case Event.CONNECT: case Event.CONNECT_WITH_STATE_TRANSFER: case Event.CONNECT_USE_FLUSH: case Event.CONNECT_WITH_STATE_TRANSFER_USE_FLUSH: thread_local.set(this); cluster_name=(String)evt.getArg(); factory.setClusterName(cluster_name); this.header=new TpHeader(cluster_name); break; case Event.SET_LOCAL_ADDRESS: Address addr=(Address)evt.getArg(); if(addr != null) { local_addr=addr; factory.setAddress(addr.toString()); // used for thread naming } break; } return down_prot.down(evt); } public String getName() { return "TP.ProtocolAdapter"; } public String toString() { return cluster_name + " (" + transport_name + ")"; } public Map<String, String> handleProbe(String... keys) { HashMap<String, String> retval=new HashMap<String, String>(); retval.put("cluster", cluster_name); retval.put("local_addr", local_addr != null? local_addr.toString() : null); retval.put("local_addr (UUID)", local_addr instanceof UUID? ((UUID)local_addr).toStringLong() : null); retval.put("transport_name", transport_name); return retval; } public String[] supportedKeys() { return null; } } }
package org.joni; import org.jcodings.Encoding; import org.joni.exception.ErrorMessages; import org.joni.exception.ValueException; public final class CodeRangeBuffer { private static final int INIT_MULTI_BYTE_RANGE_SIZE = 5; public static final int LAST_CODE_POINT = 0x7fffffff; private int[]p; private int used; public CodeRangeBuffer() { p = new int[INIT_MULTI_BYTE_RANGE_SIZE]; writeCodePoint(0, 0); } public int[]getCodeRange() { return p; } public int getUsed() { return used; } private CodeRangeBuffer(CodeRangeBuffer orig) { p = new int[orig.p.length]; System.arraycopy(orig.p, 0, p, 0, p.length); used = orig.used; } public void expand(int low) { int length = p.length; do { length <<= 1; } while (length < low); int[]tmp = new int[length]; System.arraycopy(p, 0, tmp, 0, used); p = tmp; } public void ensureSize(int size) { int length = p.length; while (length < size ) { length <<= 1; } if (p.length != length) { int[]tmp = new int[length]; System.arraycopy(p, 0, tmp, 0, used); p = tmp; } } private void moveRight(int from, int to, int n) { if (to + n > p.length) expand(to + n); System.arraycopy(p, from, p, to, n); if (to + n > used) used = to + n; } protected void moveLeft(int from, int to, int n) { System.arraycopy(p, from, p, to, n); } private void moveLeftAndReduce(int from, int to) { System.arraycopy(p, from, p, to, used - from); used -= from - to; } public void writeCodePoint(int pos, int b) { int u = pos + 1; if (p.length < u) expand(u); p[pos] = b; if (used < u) used = u; } public CodeRangeBuffer clone() { return new CodeRangeBuffer(this); } // add_code_range_to_buf public static CodeRangeBuffer addCodeRangeToBuff(CodeRangeBuffer pbuf, ScanEnvironment env, int from, int to) { return addCodeRangeToBuff(pbuf, env, from, to, true); } public static CodeRangeBuffer addCodeRangeToBuff(CodeRangeBuffer pbuf, ScanEnvironment env, int from, int to, boolean checkDup) { if (from > to) { int n = from; from = to; to = n; } if (pbuf == null) pbuf = new CodeRangeBuffer(); // move to CClassNode int[]p = pbuf.p; int n = p[0]; int bound = from == 0 ? 0 : n; int low = 0; while (low < bound) { int x = (low + bound) >>> 1; if (from - 1 > p[x * 2 + 2]) { low = x + 1; } else { bound = x; } } int high = to == LAST_CODE_POINT ? n : low; bound = n; while (high < bound) { int x = (high + bound) >>> 1; if (to + 1 >= p[x * 2 + 1]) { high = x + 1; } else { bound = x; } } int incN = low + 1 - high; if (n + incN > Config.MAX_MULTI_BYTE_RANGES_NUM) throw new ValueException(ErrorMessages.ERR_TOO_MANY_MULTI_BYTE_RANGES); if (incN != 1) { if (checkDup) { if (from <= p[low * 2 + 2] && (p[low * 2 + 1] <= from || p[low * 2 + 2] <= to)) env.ccDuplicateWarn(); } if (from > p[low * 2 + 1]) from = p[low * 2 + 1]; if (to < p[(high - 1) * 2 + 2]) to = p[(high - 1) * 2 + 2]; } if (incN != 0) { int fromPos = 1 + high * 2; int toPos = 1 + (low + 1) * 2; if (incN > 0) { if (high < n) { int size = (n - high) * 2; pbuf.moveRight(fromPos, toPos, size); } } else { pbuf.moveLeftAndReduce(fromPos, toPos); } } int pos = 1 + low * 2; // pbuf.ensureSize(pos + 2); pbuf.writeCodePoint(pos, from); pbuf.writeCodePoint(pos + 1, to); n += incN; pbuf.writeCodePoint(0, n); return pbuf; } // add_code_range, be aware of it returning null! public static CodeRangeBuffer addCodeRange(CodeRangeBuffer pbuf, ScanEnvironment env, int from, int to) { return addCodeRange(pbuf, env, from, to, true); } public static CodeRangeBuffer addCodeRange(CodeRangeBuffer pbuf, ScanEnvironment env, int from, int to, boolean checkDup) { if (from >to) { if (env.syntax.allowEmptyRangeInCC()) { return pbuf; } else { throw new ValueException(ErrorMessages.ERR_EMPTY_RANGE_IN_CHAR_CLASS); } } return addCodeRangeToBuff(pbuf, env, from, to, checkDup); } private static int mbcodeStartPosition(Encoding enc) { return enc.minLength() > 1 ? 0 : 0x80; } // SET_ALL_MULTI_BYTE_RANGE protected static CodeRangeBuffer setAllMultiByteRange(ScanEnvironment env, CodeRangeBuffer pbuf) { return addCodeRangeToBuff(pbuf, env, mbcodeStartPosition(env.enc), LAST_CODE_POINT); } // ADD_ALL_MULTI_BYTE_RANGE public static CodeRangeBuffer addAllMultiByteRange(ScanEnvironment env, CodeRangeBuffer pbuf) { if (!env.enc.isSingleByte()) return setAllMultiByteRange(env, pbuf); return pbuf; } // not_code_range_buf public static CodeRangeBuffer notCodeRangeBuff(ScanEnvironment env, CodeRangeBuffer bbuf) { CodeRangeBuffer pbuf = null; if (bbuf == null) return setAllMultiByteRange(env, pbuf); int[]p = bbuf.p; int n = p[0]; if (n <= 0) return setAllMultiByteRange(env, pbuf); int pre = mbcodeStartPosition(env.enc); int from; int to = 0; for (int i=0; i<n; i++) { from = p[i * 2 + 1]; to = p[i * 2 + 2]; if (pre <= from - 1) { pbuf = addCodeRangeToBuff(pbuf, env, pre, from - 1); } if (to == LAST_CODE_POINT) break; pre = to + 1; } if (to < LAST_CODE_POINT) pbuf = addCodeRangeToBuff(pbuf, env, to + 1, LAST_CODE_POINT); return pbuf; } // or_code_range_buf public static CodeRangeBuffer orCodeRangeBuff(ScanEnvironment env, CodeRangeBuffer bbuf1, boolean not1, CodeRangeBuffer bbuf2, boolean not2) { CodeRangeBuffer pbuf = null; if (bbuf1 == null && bbuf2 == null) { if (not1 || not2) { return setAllMultiByteRange(env, pbuf); } return null; } if (bbuf2 == null) { CodeRangeBuffer tbuf; boolean tnot; // swap tnot = not1; not1 = not2; not2 = tnot; tbuf = bbuf1; bbuf1 = bbuf2; bbuf2 = tbuf; } if (bbuf1 == null) { if (not1) { return setAllMultiByteRange(env, pbuf); } else { if (!not2) { return bbuf2.clone(); } else { return notCodeRangeBuff(env, bbuf2); } } } if (not1) { CodeRangeBuffer tbuf; boolean tnot; // swap tnot = not1; not1 = not2; not2 = tnot; tbuf = bbuf1; bbuf1 = bbuf2; bbuf2 = tbuf; } if (!not2 && !not1) { /* 1 OR 2 */ pbuf = bbuf2.clone(); } else if (!not1) { /* 1 OR (not 2) */ pbuf = notCodeRangeBuff(env, bbuf2); } int[]p1 = bbuf1.p; int n1 = p1[0]; for (int i=0; i<n1; i++) { int from = p1[i * 2 + 1]; int to = p1[i * 2 + 2]; pbuf = addCodeRangeToBuff(pbuf, env, from, to); } return pbuf; } // and_code_range1 public static CodeRangeBuffer andCodeRange1(CodeRangeBuffer pbuf, ScanEnvironment env, int from1, int to1, int[]data, int n) { for (int i=0; i<n; i++) { int from2 = data[i * 2 + 1]; int to2 = data[i * 2 + 2]; if (from2 < from1) { if (to2 < from1) { continue; } else { from1 = to2 + 1; } } else if (from2 <= to1) { if (to2 < to1) { if (from1 <= from2 - 1) { pbuf = addCodeRangeToBuff(pbuf, env, from1, from2 - 1); } from1 = to2 + 1; } else { to1 = from2 - 1; } } else { from1 = from2; } if (from1 > to1) break; } if (from1 <= to1) { pbuf = addCodeRangeToBuff(pbuf, env, from1, to1); } return pbuf; } // and_code_range_buf public static CodeRangeBuffer andCodeRangeBuff(CodeRangeBuffer bbuf1, boolean not1, CodeRangeBuffer bbuf2, boolean not2, ScanEnvironment env) { CodeRangeBuffer pbuf = null; if (bbuf1 == null) { if (not1 && bbuf2 != null) return bbuf2.clone(); /* not1 != 0 -> not2 == 0 */ return null; } else if (bbuf2 == null) { if (not2) return bbuf1.clone(); return null; } if (not1) { CodeRangeBuffer tbuf; boolean tnot; // swap tnot = not1; not1 = not2; not2 = tnot; tbuf = bbuf1; bbuf1 = bbuf2; bbuf2 = tbuf; } int[]p1 = bbuf1.p; int n1 = p1[0]; int[]p2 = bbuf2.p; int n2 = p2[0]; if (!not2 && !not1) { /* 1 AND 2 */ for (int i=0; i<n1; i++) { int from1 = p1[i * 2 + 1]; int to1 = p1[i * 2 + 2]; for (int j=0; j<n2; j++) { int from2 = p2[j * 2 + 1]; int to2 = p2[j * 2 + 2]; if (from2 > to1) break; if (to2 < from1) continue; int from = from1 > from2 ? from1 : from2; int to = to1 < to2 ? to1 : to2; pbuf = addCodeRangeToBuff(pbuf, env, from, to); } } } else if (!not1) { /* 1 AND (not 2) */ for (int i=0; i<n1; i++) { int from1 = p1[i * 2 + 1]; int to1 = p1[i * 2 + 2]; pbuf = andCodeRange1(pbuf, env, from1, to1, p2, n2); } } return pbuf; } public String toString() { StringBuilder buf = new StringBuilder(); buf.append("CodeRange"); buf.append("\n used: " + used); buf.append(", size: " + p[0]); buf.append("\n ranges: "); for (int i=0; i<p[0]; i++) { buf.append("[" + rangeNumToString(p[i * 2 + 1]) + ".." + rangeNumToString(p[i * 2 + 2]) + "]"); if (i > 0 && i % 6 == 0) buf.append("\n "); } return buf.toString(); } private static String rangeNumToString(int num){ return "0x" + Integer.toString(num, 16); } }
/* * $Id: I18nUtil.java,v 1.2 2012-07-22 01:40:21 pgust Exp $ */ package org.lockss.util; import java.util.MissingResourceException; import org.lockss.util.Logger; import org.xnap.commons.i18n.I18n; import org.xnap.commons.i18n.I18nFactory; /** * A utility class for I18N features. * * @author Neil Mayo */ public class I18nUtil { protected static Logger log = Logger.getLogger("I18nUtil"); /** The name of the default backup bundle. This should always be in the build. */ private static final String defaultBundle = "DefaultBundle"; /** * Get a gettext-commons I18n object suitable for performing * localisation of strings. If the gettext bundles are not available, * it will use the defaultBundle, which does no translation but does * perform formatting for strings with arguments. * <p> * The gettext-commons library internally caches the I18n objects. * * @param clazz the class of the caller * @return an I18n object */ public static I18n getI18n(Class clazz) { I18n i18n; try { i18n = I18nFactory.getI18n(clazz); } catch (MissingResourceException ex) { log.error("Cannot initialize i18n for "+clazz, ex); // Try again, specifying the default bundle try { i18n = I18nFactory.getI18n(clazz, defaultBundle); log.warning("i18n is disabled: using "+defaultBundle); } catch (MissingResourceException e) { log.critical("Cannot initialize "+defaultBundle+" for "+clazz, e); i18n = null; // This shouldn't happen if the DefaultBundle is incorporated into the // build. Is the omission a serious enough build error to stop the daemon? } } return i18n; } }
package org.ms2ms.algo; import com.google.common.collect.Lists; import com.google.common.collect.Table; import com.hfg.bio.Element; import org.expasy.mzjava.core.ms.peaklist.Peak; import org.ms2ms.data.collect.ImmutableNavigableMap; import org.ms2ms.data.ms.IsoEnvelope; import org.ms2ms.data.ms.OffsetPpmTolerance; import org.ms2ms.data.ms.PeakMatch; import org.ms2ms.math.Stats; import org.ms2ms.mzjava.AnnotatedPeak; import org.ms2ms.utils.Tools; import java.io.*; import java.util.*; public class Isotopics { // initialization methods final double ELECTRON_MASS = 0.00054858; final double DUMMY_MASS = -10000000; final double AVERAGINE_MASS = 111.0543052; final double DELTA_C13 = 1.00335d; Map<String, Long> EM = new HashMap<String, Long>(); List<List<List<Peak>>> SAD = new ArrayList<List<List<Peak>>>(); Map<Integer, List<Peak>> mMassIso = new HashMap<>(); // public static Histogram dp_prediction = new Histogram(); public Isotopics() { try { init_data(Isotopes.class.getClassLoader().getResourceAsStream("org/ms2ms/algo/ISOTOPE.DAT"), SAD, EM); } catch (IOException e) { e.printStackTrace(); } } public List<Peak> predictEnvelope(double c12, int charge, double minri) { Integer mass = (int )c12 * charge; List<Peak> result = mMassIso.get(mass); if (result==null) { // initialize the result result = new ArrayList<>(); result.add(new Peak(0.0, 1.0)); result = calculate(new ArrayList<>(), result, newFormulaMapByAveragine(mass), 0, charge); Iterator<Peak> itr = result.iterator(); while (itr.hasNext()) if (itr.next().getIntensity() < minri) itr.remove(); mMassIso.put(mass, result); } // a nasty bug, WYU 20170625 else if (result.get(0).getCharge()!=charge) { // make sure the charge states are right List<Peak> results = new ArrayList<>(result.size()); for (Peak p : result) results.add(new Peak(Peaks.MnH2MnH(p.getMz(), p.getCharge(), charge), p.getIntensity(), charge)); return results; } return result; } public IsoEnvelope calcIsotopesByMz(double c12, int charge, double minri, double ai) { List<Peak> result = predictEnvelope(c12, charge, minri); // move the predictions to the c12 double offset = c12 - result.get(0).getMz(); // scale the ai to the 1st c12 ai /= result.get(0).getIntensity(); List<Peak> isotopes = new ArrayList<>(); for (Peak pk : result) isotopes.add(new Peak(pk.getMz()+offset, ai*pk.getIntensity(), pk.getChargeList())); IsoEnvelope iso = new IsoEnvelope(isotopes, charge); Tools.dispose(isotopes); return iso; } public List<Peak> calculate(List<Peak> tmp, List<Peak> result, Map<Integer, Long> fm, double limit, long charge) { for (Map.Entry<Integer, Long> i : fm.entrySet()) { Integer atom_index = i.getKey(); List<List<Peak>> sal = SAD.get(atom_index); Long n = i.getValue(); int j = 0; while(n > 0) { int sz = sal.size(); if (j == sz) { // expand the list sal.add(new ArrayList<Peak>()); // Make new superatom from previous largest superatom. We are trying to avoid copying on assignment here. convolute_basic(sal.get(j), sal.get(j - 1), sal.get(j - 1)); prune(sal.get(j), limit); } if((n & 1) != 0L) // digit is 1, convolute result { convolute_basic(tmp , result, sal.get(j)); prune(tmp, limit); // Hopefully the swap implementation will not copy all elements. List<Peak> intermediate = new ArrayList<Peak>(tmp); tmp.clear(); tmp.addAll(result); result.clear(); result.addAll(intermediate); } n >>>= 1; j++; } } // take charge into account for(Peak pk : result) { if (charge > 0) pk.setMzAndCharge(pk.getMz() / Math.abs(charge) - ELECTRON_MASS, (int) charge); else if (charge < 0) pk.setMzAndCharge(pk.getMz() / Math.abs(charge) + ELECTRON_MASS, (int )charge); } return result; } // Merge two patterns to one. public void convolute_basic(List<Peak> h, final List<Peak> g, final List<Peak> f) { h.clear(); int g_n = g.size(), f_n = f.size(); if(g_n == 0 || f_n == 0) return; for (int k = 0; k < g_n + f_n - 1; k++) { double sumweight = 0, summass = 0; int start = k < (f_n - 1) ? 0 : k - f_n + 1, // max(0, k-f_n+1) end = k < (g_n - 1) ? k : g_n - 1; // min(g_n - 1, k) for(int i = start; i <= end; i++) { double weight = g.get(i).getIntensity() * f.get(k - i).getIntensity(); double mass = g.get(i).getMz() + f.get(k - i).getMz(); sumweight += weight; summass += weight * mass; } h.add(new Peak(sumweight == 0 ? DUMMY_MASS : summass / sumweight, sumweight)); } } // Prune the small peaks from both sides but leave them within the pattern. public void prune(List<Peak> f, double limit) { // prune the front ListIterator<Peak> itr = f.listIterator(); while (itr.hasNext()) if(itr.next().getIntensity() <= limit) itr.remove(); // prune the end itr = f.listIterator(); while(itr.hasPrevious()) { if(f.size() == 0) break; if(itr.previous().getIntensity() <= limit) itr.remove(); } } // script: RMS (weighted) (ATGC)1000 public void print_pattern(List<Peak> result, int digits) { // find the maximum double max_area = 0; for(Peak pk : result) { if(max_area < pk.getIntensity()) max_area = pk.getIntensity(); } if(max_area == 0) return; // empty pattern double print_limit = Math.pow(10.0, -digits) / 2; for(Peak pk : result) { double mass = pk.getMz(); double rel_area = pk.getIntensity(); double val_perc = rel_area / max_area * 100; if(mass != DUMMY_MASS && val_perc >= print_limit) System.out.println(Tools.d2s(mass, digits) + " " + Tools.d2s(val_perc, digits)); } } public Map<Integer, Long> newFormulaMapByAveragine(double c12) { // C4.9384 H7.7583 N1.3577 O1.4773 S0.0417 double multiple = c12 / AVERAGINE_MASS; Map<Integer, Long> formula = new HashMap<Integer, Long>(); formula = increFormulaMap(formula, EM, Element.CARBON, Math.round(4.9384 * multiple)); formula = increFormulaMap(formula, EM, Element.HYDROGEN, Math.round(7.7583 * multiple)); formula = increFormulaMap(formula, EM, Element.NITROGEN, Math.round(1.3577 * multiple)); formula = increFormulaMap(formula, EM, Element.OXYGEN, Math.round(1.4773 * multiple)); formula = increFormulaMap(formula, EM, Element.SULFUR, Math.round(0.0417 * multiple)); return formula; } public Map<Integer, Long> increFormulaMap(Map<Integer, Long> formula, Map<String, Long> em, Element el, long atoms) { // cells the element index int index = em.get(el.getSymbol()).intValue(); formula.put(index, atoms + (formula.get(index) != null ? formula.get(index) : 0)); return formula; } private boolean init_data(InputStream dat, List<List<List<Peak>>> sad, Map<String, Long> em) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(dat)); sad.clear(); em.clear(); long elemindex = 0; int state = 0; List<List<Peak>> current = null; while(reader.ready()) { String[] strs = reader.readLine().split("\\s+"); String element; if (state == 0) { element = strs[0]; em.put(element, elemindex); current = new ArrayList<List<Peak>>(); sad.add(current); elemindex++; state = 1; } else if (state == 1) // isotope { try { Peak p = new Peak(new Double(strs[0]), new Double(strs[1])); if (current.size() == 0) current.add(new ArrayList<Peak>()); List<Peak> idist = current.get(0); // fill the gaps in the patterns with zero abundancy peaks if(idist.size() > 0) { double prevmass = Tools.back(idist).getMz(); for(int i = 0; i < (int )(p.getMz() - prevmass - 0.5); i++) idist.add(new Peak(DUMMY_MASS, 0)); } // insert the peak idist.add(p); } catch (NumberFormatException e) { //e.printStackTrace(); state = 0; // no more isotope data } } } reader.close(); EM = em; return true; } public IsoEnvelope gatherIsotopes(ImmutableNavigableMap<PeakMatch> peaks, double mz, double mh, OffsetPpmTolerance tol) { // return null, if has negative intensity IsoEnvelope iso = PeakMatch.query4isotope(peaks, mz, tol, false); // for large peptide, also check the 1st c13 if (iso==null && mz>1000) { iso = PeakMatch.query4isotope(peaks, mz+Peptides.C13, tol, false); if (iso!=null) iso = new IsoEnvelope(iso.getMz()-Peptides.C13, iso.getIntensity(), 0).setScore(iso.getScore()); } // quit if not matching to the first mz! if (iso!=null) { iso.setMz(iso.getMz()).setCharge((int) Math.round(mh/iso.getMz())); // check for any below m/z if (PeakMatch.query4counts(peaks, tol, mz-(1.0025/(double) iso.getCharge()))>0) { // got an incorrect c12! iso.setChargeScore(-1); } else { iso.setChargeScore(1d); // looking forward for (int i=1; i<iso.getCharge()+1; i++) { double ai = PeakMatch.query4ai(peaks, mz+(i*1.0025/(double) iso.getCharge()), tol); if (ai<=0) break; iso.setChargeScore(iso.getChargeScore()+1d); iso.setIntensity(iso.getIntensity()+ai); } } return iso; } return null; } // // deprecated // public IsoEnvelope gatherIsotopes(ImmutableNavigableMap<PeakMatch> peaks, double mz, double mh, OffsetPpmTolerance tol) // int[] mz_ai = peaks.query(tol.toActualBoundary(mz)); // PeakMatch[] matched = peaks.fetchVals(mz_ai); // // quit if not matching to the first mz! // if (matched!=null && !PeakMatch.hasNegativeIntensity(matched)) // IsoEnvelope iso = new IsoEnvelope(); // iso.setMzAndCharge(Stats.mean0(peaks.fetchKeys(mz_ai)), 0); // iso.setMzAndCharge(iso.getMz(), (int) Math.round(mh/iso.getMz())); // iso.setIntensity(PeakMatch.AbsIntensitySum(matched)); // iso.setScore(matched[0].getFrequency()); // // check for any below m/z // double[] bound = tol.toActualBoundary(mz-(1.0025/(double) iso.getCharge())); // mz_ai=peaks.query(bound); // if (mz_ai!=null) // // got an incorrect c12! // iso.setChargeScore(-1); // else // iso.setChargeScore(1d); // // looking forward // for (int i=1; i<iso.getCharge()+1; i++) // bound = tol.toActualBoundary(mz+(i*1.0025/(double) iso.getCharge())); // mz_ai = peaks.query(bound); // if (mz_ai==null) break; // matched = peaks.fetchVals(mz_ai); // iso.setChargeScore(iso.getChargeScore()+1d); // iso.setIntensity(iso.getIntensity()+PeakMatch.AbsIntensitySum(matched)); // matched=null; mz_ai=null; bound=null; // bound=null; mz_ai=null; matched=null; // return iso; // mz_ai=null; matched=null; // return null; }
package org.osb; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ScrollView; import android.widget.TextView; import android.widget.ViewFlipper; public class ScheduleActivity extends AbstractActivity { private static final Date JUN1 = new Date(110, 5, 1); private static final Date JUN2 = new Date(110, 5, 2); private static final Date JUN3 = new Date(110, 5, 3); private static final Date JUN4 = new Date(110, 5, 4); private static final int MENU_JUN1 = 1; private static final int MENU_JUN2 = 2; private static final int MENU_JUN3 = 3; private static final int MENU_JUN4 = 4; private static final int MENU_NEXT = 5; private static final int MENU_PREV = 6; private static final int MENU_ABOUT = 7; private static final int MENU_NOW = 8; private static final int MENU_REFRESH = 9; // state Date mCurrentDate; TextView mDate; boolean mDetail = false; Handler mHandler; // general conference data Conference mConference; Date[] mDates; // session list EventAdapter mAdapter; ListView mEvents; // screen animation ViewFlipper mFlipper; Animation mInLeft; Animation mInRight; Animation mOutLeft; Animation mOutRight; // session details Event mEvent = null; HashMap<Integer, Speaker> mSpeakers; View mHeader; TextView mTitle; TextView mTime; TextView mLocation; View mTimeLocation; TextView mSpeaker; ScrollView mDescriptionScroller; TextView mDescription; ImageView mMapImage; LinearLayout mBio; // session detail actions Button mFoursquare; Button mShare; Button mMap; Button mShowDescription; Button mShowBio; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mHandler = new Handler(); mSpeakers = new HashMap<Integer, Speaker>(); mDate = (TextView) findViewById(R.id.date); mEvents = (ListView) findViewById(R.id.events); mFlipper = (ViewFlipper) findViewById(R.id.flipper); Context context = getApplicationContext(); mInLeft = AnimationUtils.loadAnimation(context, R.anim.slide_in_left); mInRight = AnimationUtils.loadAnimation(context, R.anim.slide_in_right); mOutLeft = AnimationUtils.loadAnimation(context, R.anim.slide_out_left); mOutRight = AnimationUtils.loadAnimation(context, R.anim.slide_out_right); // grab views for details View detail = findViewById(R.id.detail); mHeader = findViewById(R.id.detail_header); mSpeaker = (TextView) findViewById(R.id.speaker); mTitle = (TextView) detail.findViewById(R.id.title); mTimeLocation = detail.findViewById(R.id.time_location); mTime = (TextView) detail.findViewById(R.id.time); mLocation = (TextView) detail.findViewById(R.id.location); mDescription = (TextView) detail.findViewById(R.id.description); mDescriptionScroller = (ScrollView) detail.findViewById(R.id.description_scroller); mMapImage = (ImageView) detail.findViewById(R.id.map_image); mBio = (LinearLayout) detail.findViewById(R.id.bio); // detail action buttons mFoursquare = (Button) findViewById(R.id.foursquare); mShare = (Button) findViewById(R.id.share); mMap = (Button) findViewById(R.id.map); mShowDescription = (Button) findViewById(R.id.show_description); mShowBio = (Button) findViewById(R.id.show_bio); mEvents.setOnItemClickListener(new ListView.OnItemClickListener() { public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) { Object item = mAdapter.mFiltered.get(position); if (item instanceof Date) { return;// ignore clicks on the dates } Event event = (Event) item; Context context = getApplicationContext(); Track track = mConference.tracks.get(event.track); mHeader.setBackgroundColor(track.color); mTitle.setText(event.title); mLocation.setText(event.location); DateFormat startFormat = new SimpleDateFormat("E, h:mm"); DateFormat endFormat = new SimpleDateFormat("h:mm a"); String timeString = startFormat.format(event.start) + " - " + endFormat.format(event.end); mTime.setText(timeString); mSpeaker.setText(event.speakers); mTimeLocation.setBackgroundColor(track.color); mDescription.setText(event.description); show_description(); mDescriptionScroller.scrollTo(0, 0); mFlipper.setInAnimation(mInRight); mFlipper.setOutAnimation(mOutLeft); mFlipper.showNext(); mEvent = event; mDetail = true; } }); mShowDescription.setOnClickListener(new OnClickListener() { public void onClick(View v) { show_description(); } }); mMap.setOnClickListener(new OnClickListener() { public void onClick(View v) { mMapImage.setImageResource(getMapResource(mLocation.getText())); mDescription.setVisibility(View.GONE); mBio.setVisibility(View.GONE); mMapImage.setVisibility(View.VISIBLE); } private int getMapResource(CharSequence roomName) { if (roomName.equals("Hawthorne")) { return R.drawable.hawthorne; } else if (roomName.equals("Burnside")) { return R.drawable.burnside; } else if (roomName.equals("St. Johns")) { return R.drawable.st_johns; } else if (roomName.equals("Broadway")) { return R.drawable.broadway; } else if (roomName.equals("Morrison")) { return R.drawable.morrison; } else if (roomName.equals("Fremont")) { return R.drawable.fremont; } else if (roomName.equals("Steel")) { return R.drawable.steel; } return R.drawable.icon_footer; } }); mShowBio.setOnClickListener(new OnClickListener() { public void onClick(View v) { mBio.removeAllViews(); Integer[] speaker_ids = mEvent.speaker_ids; if (speaker_ids != null) { for (int i=0; i<speaker_ids.length; i++) { View view = loadBioView(speaker_ids[i]); if (view != null) { if (i>0){ view.setPadding(0, 30, 0, 0); } mBio.addView(view); } } mDescription.setVisibility(View.GONE); mMapImage.setVisibility(View.GONE); mBio.setVisibility(View.VISIBLE); } } /** * loads a view populated with the speakers info * @param id * @return */ private View loadBioView(int sid) { Integer id = new Integer(sid); Speaker speaker = null; View view = null; // check memory to see if speaker had already been loaded // else load the speaker from persistent storage if (mSpeakers.containsKey(id)){ speaker = mSpeakers.get(id); } else { speaker = getDataService().getSpeaker(id, false); mSpeakers.put(id, speaker); } // create view if (speaker != null) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = vi.inflate(R.layout.bio, null); TextView name = (TextView) view.findViewById(R.id.name); name.setText(speaker.name); TextView biography = (TextView) view.findViewById(R.id.biography); biography.setText(speaker.biography); String twitter = speaker.twitter; if (twitter != null && twitter != "" && twitter != "null"){ TextView text = (TextView) view.findViewById(R.id.twitter); text.setText(twitter); View parent = (View) text.getParent(); parent.setVisibility(View.VISIBLE); } String website = speaker.website; if (website != null && website != "" && website != "null"){ TextView text = (TextView) view.findViewById(R.id.website); text.setText(speaker.website); View parent = (View) text.getParent(); parent.setVisibility(View.VISIBLE); } String blog = speaker.blog; if (blog != null && blog != "" && blog != "null"){ TextView text = (TextView) view.findViewById(R.id.blog); text.setText(speaker.blog); View parent = (View) text.getParent(); parent.setVisibility(View.VISIBLE); } if (speaker.affiliation != null){ TextView text = (TextView) view.findViewById(R.id.affiliation); text.setText(speaker.affiliation); } String identica = speaker.identica; if (identica != null && identica != "" && identica != "null"){ TextView text = (TextView) view.findViewById(R.id.identica); text.setText(speaker.identica); View parent = (View) text.getParent(); parent.setVisibility(View.VISIBLE); } } return view; } }); mFoursquare.setOnClickListener(new OnClickListener() { public void onClick(View v) { String url = mapRoomNameToFqUrl((mLocation).getText().toString()); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); } private String mapRoomNameToFqUrl(String roomName) { String vid = ""; if (roomName.equals("Hawthorne")) { vid = "4281683"; } else if (roomName.equals("Burnside")) { vid = "4281826"; } else if (roomName.equals("St. Johns")) { vid = "4281970"; } else if (roomName.equals("Broadway")) { vid = "4281777"; } else if (roomName.equals("Morrison")) { vid = "4281923"; } else if (roomName.equals("Fremont")) { vid = "4281874"; } else if (roomName.equals("Steel")) { vid = "4282004"; } return "http://m.foursquare.com/checkin?vid="+vid; } }); mShare.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(android.content.Intent.ACTION_SEND); intent.setType("text/plain"); Resources r = getApplicationContext().getResources(); intent.putExtra(Intent.EXTRA_SUBJECT, r.getString(R.string.share_subject)); intent.putExtra(Intent.EXTRA_TEXT, r.getString(R.string.share_text) + mTitle.getText() + r.getString(R.string.share_text2)); startActivity(Intent.createChooser(intent, "Share")); } }); // spawn loading into separate thread mHandler.post(new Runnable() { public void run() { loadSchedule(false); now(); } }); } /** * Shows the session description, hides all other subviews */ private void show_description(){ mMapImage.setVisibility(View.GONE); mBio.setVisibility(View.GONE); mDescription.setVisibility(View.VISIBLE); } /** * overridden to hook back button when on the detail page */ public boolean onKeyDown(int keyCode, KeyEvent event){ if (mDetail && keyCode == KeyEvent.KEYCODE_BACK){ showList(); return true; } return super.onKeyDown(keyCode, event); } /* Creates the menu items */ public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, MENU_PREV, 0, "Previous Day").setIcon(R.drawable.ic_menu_back); SubMenu dayMenu = menu.addSubMenu("Day").setIcon(android.R.drawable.ic_menu_today); dayMenu.add(0, MENU_JUN1, 0, "Tuesday, June 1"); dayMenu.add(0, MENU_JUN2, 0, "Wednesday, June 2"); dayMenu.add(0, MENU_JUN3, 0, "Thursday, June 3"); dayMenu.add(0, MENU_JUN4, 0, "Friday, June 4"); menu.add(0, MENU_NEXT, 0, "Next Day").setIcon(R.drawable.ic_menu_forward); menu.add(0, MENU_NOW, 0, "Now").setIcon(android.R.drawable.ic_menu_mylocation); menu.add(0, MENU_REFRESH, 0, "Refresh").setIcon(R.drawable.ic_menu_refresh); menu.add(0, MENU_ABOUT, 0, "About").setIcon(android.R.drawable.ic_menu_info_details); return true; } /* Handles item selections */ public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_NOW: now(); return true; case MENU_JUN1: setDay(JUN1); return true; case MENU_JUN2: setDay(JUN2); return true; case MENU_JUN3: setDay(JUN3); return true; case MENU_JUN4: setDay(JUN4); return true; case MENU_PREV: previous(); return true; case MENU_NEXT: next(); return true; case MENU_ABOUT: showDialog(0); return true; case MENU_REFRESH: mHandler.post(new Runnable() { public void run() { loadSchedule(true); now(); } }); return true; } return false; } /* sets the current day, filtering the list if need be */ public void setDay(Date date) { if (isSameDay(mCurrentDate, date)) { // same day, just jump to current time mAdapter.now(date); } else { // different day, update the list mCurrentDate = date; mAdapter.filterDay(date); DateFormat formatter = new SimpleDateFormat("E, MMMM d"); mDate.setText(formatter.format(mCurrentDate)); } // take user back to the listings if not already there showList(); } /** * Jumps the user to right now in the event list: * * - if its before or after the conference, it shows the beginning * of day 1 * - if its during the conference it will show the first event * currently underway */ public void now(){ Date now = new Date(); if (now.before(mDates[0]) || now.after(mConference.end)) { setDay(mDates[0]); } else { // use now, since it will have the time of day for // jumping to the right time setDay(now); } } /** * Jumps to the next day, if not already at the end */ public void next() { try { if (!isSameDay(mCurrentDate, mConference.end)) { mCurrentDate.setDate(mCurrentDate.getDate()+1); mCurrentDate.setHours(0); mCurrentDate.setMinutes(0); setDay(mCurrentDate); } } catch (Exception e) { e.printStackTrace(); } } /** * Jumps to the previous day if now already at the beginning */ public void previous() { if (!isSameDay(mCurrentDate, mConference.start)) { mCurrentDate.setDate(mCurrentDate.getDate()-1); mCurrentDate.setHours(0); mCurrentDate.setMinutes(0); setDay(mCurrentDate); } } /** * Shows the event listing */ public void showList() { if (mDetail) { mFlipper.setInAnimation(mInLeft); mFlipper.setOutAnimation(mOutRight); mFlipper.showPrevious(); mDetail=false; } } /** * Loads the osbridge schedule from a combination of ICal and json data * @param force - force reload */ private void loadSchedule(boolean force) { System.out.println("================Schedule================"); //XXX set date to a day that is definitely, not now. // This will cause it to update the list immediately. mCurrentDate = new Date(1900, 0, 0); DataService service = getDataService(); mConference = service.getConference(force); try { mDates = mConference.getDates(); ICal calendar = new ICal(); Schedule schedule = service.getSchedule(force); calendar.setEvents(schedule.events); mAdapter = new EventAdapter(this, R.layout.listevent, calendar.getEvents()); mEvents.setAdapter(mAdapter); } catch (Exception e) { e.printStackTrace(); } System.out.println("================Schedule================"); } /** * parse events from json file and update the given calendar * @param calendar * @param force - force refresh */ private void parseProposals(ICal calendar, boolean force){ Schedule sched = getDataService().getSchedule(force); calendar.setEvents(sched.events); } protected Dialog onCreateDialog(int id){ Context context = getApplicationContext(); LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE); View v = inflater.inflate(R.layout.about, null); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("About"); builder.setCancelable(true); builder.setView(v); builder.setIcon(android.R.drawable.ic_dialog_info); final AlertDialog alert = builder.create(); return alert; } /** * EventAdapter used for displaying a list of events * */ private class EventAdapter extends ArrayAdapter<Event> { private List<Event> mItems; private List<Object> mFiltered; public EventAdapter(Context context, int textViewResourceId, List<Event> items) { super(context, textViewResourceId, items); this.mItems = items; mFiltered = new ArrayList<Object>(); } /** * Filters the list to contain only events for the given date. * @param date - date to filter by */ public void filterDay(Date date){ List<Event> items = mItems; List<Object> filtered = new ArrayList<Object>(); int size = mItems.size(); Date currentStart = null; for (int i=0; i<size; i++){ Event event = items.get(i); if(isSameDay(date, event.start)){ if(currentStart == null || event.start.after(currentStart)) { currentStart = event.start; filtered.add(currentStart); } filtered.add(event); } } mFiltered = filtered; notifyDataSetChanged(); now(date); } /** * sets the position to the current time * @param date */ public void now(Date date) { List<Object> filtered = mFiltered; int size = filtered.size(); for (int i=0; i<size; i++){ Object item = filtered.get(i); // find either the first session that hasn't ended yet // or the first time marker that hasn't occured yet. if (item instanceof Date ){ Date slot = (Date) item; if (date.before(slot)) { mEvents.setSelection(i); return; } } else { Event event = (Event) item; if (event.end.after(date)) { // should display the time marker instead of the // session mEvents.setSelection(i-1); return; } } } // no current event was found, jump to the next day next(); } public int getCount(){ return mFiltered.size(); } public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); Object item = mFiltered.get(position); if (item instanceof Date) { Date date = (Date)item; v = vi.inflate(R.layout.list_slot, null); TextView time = (TextView) v.findViewById(R.id.time); DateFormat formatter = new SimpleDateFormat("h:mm a"); time.setText(formatter.format(date)); } else { Event e = (Event) item; v = vi.inflate(R.layout.listevent, null); if (e != null) { TextView title = (TextView) v.findViewById(R.id.title); TextView location = (TextView) v.findViewById(R.id.location); TextView time = (TextView) v.findViewById(R.id.time); if (title != null) { title.setText(e.title); } if (location != null) { location.setText(e.location); } if (time != null) { DateFormat formatter = new SimpleDateFormat("h:mm"); time.setText(formatter.format(e.start) + "-" + formatter.format(e.end)); } if (e.track != -1) { Context context = getApplicationContext(); TextView track_view = (TextView) v.findViewById(R.id.track); Track track = mConference.tracks.get(e.track); track_view.setTextColor(track.color); track_view.setText(track.name); } } } return v; } } /** * Checks if two dates are the same day * @param date1 * @param date2 * @return */ public static boolean isSameDay(Date date1, Date date2) { if (date1 == null || date2 == null) { throw new IllegalArgumentException("The date must not be null"); } Calendar cal1 = Calendar.getInstance(); cal1.setTime(date1); Calendar cal2 = Calendar.getInstance(); cal2.setTime(date2); return isSameDay(cal1, cal2); } /** * Checks if two calendars are the same day * @param cal1 * @param cal2 * @return */ public static boolean isSameDay(Calendar cal1, Calendar cal2) { if (cal1 == null || cal2 == null) { throw new IllegalArgumentException("The date must not be null"); } return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)); } }
package org.sunflow.core; import java.io.IOException; import org.sunflow.PluginRegistry; import org.sunflow.image.Bitmap; import org.sunflow.image.BitmapReader; import org.sunflow.image.Color; import org.sunflow.image.BitmapReader.BitmapFormatException; import org.sunflow.image.formats.BitmapBlack; import org.sunflow.math.MathUtils; import org.sunflow.math.OrthoNormalBasis; import org.sunflow.math.Vector3; import org.sunflow.system.FileUtils; import org.sunflow.system.UI; import org.sunflow.system.UI.Module; /** * Represents a 2D texture, typically used by {@link Shader shaders}. */ public class Texture { private String filename; private boolean isLinear; private Bitmap bitmap; private int loaded; /** * Creates a new texture from the specfied file. * * @param filename image file to load * @param isLinear is the texture gamma corrected already? */ Texture(String filename, boolean isLinear) { this.filename = filename; this.isLinear = isLinear; loaded = 0; } private synchronized void load() { if (loaded != 0) return; String extension = FileUtils.getExtension(filename); try { UI.printInfo(Module.TEX, "Reading texture bitmap from: \"%s\" ...", filename); BitmapReader reader = PluginRegistry.bitmapReaderPlugins.createObject(extension); if (reader != null) { bitmap = reader.load(filename, isLinear); if (bitmap.getWidth() == 0 || bitmap.getHeight() == 0) bitmap = null; } if (bitmap == null) { UI.printError(Module.TEX, "Bitmap reading failed"); bitmap = new BitmapBlack(); } else UI.printDetailed(Module.TEX, "Texture bitmap reading complete: %dx%d pixels found", bitmap.getWidth(), bitmap.getHeight()); } catch (IOException e) { UI.printError(Module.TEX, "%s", e.getMessage()); } catch (BitmapFormatException e) { UI.printError(Module.TEX, "%s format error: %s", extension, e.getMessage()); } loaded = 1; } public Bitmap getBitmap() { if (loaded == 0) load(); return bitmap; } /** * Gets the color at location (x,y) in the texture. The lookup is performed * using the fractional component of the coordinates, treating the texture * as a unit square tiled in both directions. Bicubic filtering is performed * on the four nearest pixels to the lookup point. * * @param x x coordinate into the texture * @param y y coordinate into the texture * @return filtered color at location (x,y) */ public Color getPixel(float x, float y) { Bitmap bitmap = getBitmap(); x = MathUtils.frac(x); y = MathUtils.frac(y); float dx = x * (bitmap.getWidth() - 1); float dy = y * (bitmap.getHeight() - 1); int ix0 = (int) dx; int iy0 = (int) dy; int ix1 = (ix0 + 1) % bitmap.getWidth(); int iy1 = (iy0 + 1) % bitmap.getHeight(); float u = dx - ix0; float v = dy - iy0; u = u * u * (3.0f - (2.0f * u)); v = v * v * (3.0f - (2.0f * v)); float k00 = (1.0f - u) * (1.0f - v); Color c00 = bitmap.readColor(ix0, iy0); float k01 = (1.0f - u) * v; Color c01 = bitmap.readColor(ix0, iy1); float k10 = u * (1.0f - v); Color c10 = bitmap.readColor(ix1, iy0); float k11 = u * v; Color c11 = bitmap.readColor(ix1, iy1); Color c = Color.mul(k00, c00); c.madd(k01, c01); c.madd(k10, c10); c.madd(k11, c11); return c; } public Vector3 getNormal(float x, float y, OrthoNormalBasis basis) { float[] rgb = getPixel(x, y).getRGB(); return basis.transform(new Vector3(2 * rgb[0] - 1, 2 * rgb[1] - 1, 2 * rgb[2] - 1)).normalize(); } public Vector3 getBump(float x, float y, OrthoNormalBasis basis, float scale) { Bitmap bitmap = getBitmap(); float dx = 1.0f / bitmap.getWidth(); float dy = 1.0f / bitmap.getHeight(); float b0 = getPixel(x, y).getLuminance(); float bx = getPixel(x + dx, y).getLuminance(); float by = getPixel(x, y + dy).getLuminance(); return basis.transform(new Vector3(scale * (b0 - bx) / dx, scale * (b0 - by ) / dy, 1)).normalize(); } }
package com.adriencadet.downthere; /** * ApplicationConfiguration * <p> */ public class ApplicationConfiguration { public final String SERVER_ENDPOINT = "http://www38401.coshx.com"; public final int PICTURE_GRID_CACHING_MINUTES = 1; public final int TEXT_FILE_CACHING_MINUTES = 1; }
package beatprogramming.github.com.teacker_tracker; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class BDHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "TEACHER_TRACKER.db"; private static final int DATABASE_VERSION = 1; private static BDHelper bdHelper; public BDHelper(Context context) { super(context,DATABASE_NAME,null,DATABASE_VERSION); } public static void init(Context context) { bdHelper = new BDHelper(context); } public static BDHelper getInstance() { return bdHelper; } @Override public void onCreate(SQLiteDatabase db) { //- Crear BD db.execSQL(ScriptBD.ASIGNATURA_SCRIPT); db.execSQL(ScriptBD.ALUMNO_SCRIPT); db.execSQL(ScriptBD.EVALUACION_SCRIPT); db.execSQL(ScriptBD.CALIFICACION_SCRIPT); db.execSQL(ScriptBD.TAREA_SCRIPT); db.execSQL(ScriptBD.HORARIO_SCRIPT); db.execSQL(ScriptBD.MATRICULA_SCRIPT); //- Inserts predefinidos db.execSQL(ScriptBD.INSERT_ASIGNATURA1_SCRIPT); db.execSQL(ScriptBD.INSERT_ASIGNATURA2_SCRIPT); db.execSQL(ScriptBD.INSERT_TAREA1_SCRIPT); db.execSQL(ScriptBD.INSERT_TAREA2_SCRIPT); db.execSQL(ScriptBD.INSERT_TAREA3_SCRIPT); db.execSQL(ScriptBD.INSERT_REVIEW1_SCRIPT); db.execSQL(ScriptBD.INSERT_REVIEW2_SCRIPT); db.execSQL(ScriptBD.INSERT_ALUMNO1_SCRIPT); db.execSQL(ScriptBD.INSERT_ALUMNO2_SCRIPT); db.execSQL(ScriptBD.INSERT_CALIFICACION1_SCRIPT); db.execSQL(ScriptBD.INSERT_CALIFICACION2_SCRIPT); db.execSQL(ScriptBD.INSERT_CALIFICACION3_SCRIPT); db.execSQL(ScriptBD.INSERT_CALIFICACION4_SCRIPT); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //Actualizacion base de datos } }
package ca.ualberta.cmput301f17t08.habitrabbit; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import java.util.ArrayList; public class FeedActivity extends AppCompatActivity { public RecyclerView feedRecyclerView; public ArrayList<HabitEvent> feedList; public ArrayList<String> followerList; private historyAdapter cAdapt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.feed); feedRecyclerView = (RecyclerView) findViewById(R.id.feed_recycle); feedRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false)); //get the current user's feed list feedList = LoginManager.getInstance().getCurrentUser().getHistory(); //get the followers followerList = LoginManager.getInstance().getCurrentUser().getFollowers(); //testing code followerList.add("Yuxuan"); String username; ArrayList<HabitEvent> followerFeedList; // get the followers feed, and append them to the feedList for(int each = 0; each < followerList.size(); each++){ username = followerList.get(each); followerFeedList = new User(username).getHistory(); for (int index = 0; index<followerFeedList.size();index++){ feedList.add(followerFeedList.get(index)); } } // set up the adapter cAdapt = new historyAdapter(LoginManager.getInstance().getCurrentUser().getUsername(), feedList); feedRecyclerView.setAdapter(cAdapt); } public void showMenu(View v){ Intent intent = new Intent(this, MenuActivity.class); startActivity(intent); } }
package com.breadwallet.presenter.fragments; import android.app.Fragment; import android.content.pm.ApplicationInfo; import android.graphics.Bitmap; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.CardView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.webkit.ConsoleMessage; import android.webkit.JsResult; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebResourceRequest; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.LinearLayout; import com.breadwallet.R; import com.breadwallet.tools.animation.BRAnimator; import com.breadwallet.tools.animation.SlideDetector; import com.breadwallet.tools.util.Utils; import com.platform.HTTPServer; import java.net.URI; import java.net.URISyntaxException; import static com.platform.HTTPServer.URL_SUPPORT; public class FragmentSupport extends Fragment { private static final String TAG = FragmentSupport.class.getName(); public LinearLayout backgroundLayout; public CardView signalLayout; WebView webView; String theUrl; public static boolean appVisible = false; private String onCloseUrl; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_support, container, false); backgroundLayout = (LinearLayout) rootView.findViewById(R.id.background_layout); signalLayout = (CardView) rootView.findViewById(R.id.signal_layout); signalLayout.setOnTouchListener(new SlideDetector(getContext(), signalLayout)); signalLayout.setLayoutTransition(BRAnimator.getDefaultTransition()); webView = (WebView) rootView.findViewById(R.id.web_view); webView.setWebChromeClient(new BRWebChromeClient()); webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { Log.d(TAG, "shouldOverrideUrlLoading: " + request.getUrl()); Log.d(TAG, "shouldOverrideUrlLoading: " + request.getMethod()); if (onCloseUrl != null && request.getUrl().toString().equalsIgnoreCase(onCloseUrl)) { getActivity().getFragmentManager().popBackStack(); onCloseUrl = null; } else if (request.getUrl().toString().contains("_close")) { getActivity().getFragmentManager().popBackStack(); } else { view.loadUrl(request.getUrl().toString()); } return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { Log.d(TAG, "onPageStarted: " + url); super.onPageStarted(view, url, favicon); } }); theUrl = URL_SUPPORT; HTTPServer.mode = HTTPServer.ServerMode.SUPPORT; String articleId = getArguments() == null ? null : getArguments().getString("articleId"); String walletIso = getArguments() == null ? null : getArguments().getString("walletIso"); if (Utils.isNullOrEmpty(theUrl) || Utils.isNullOrEmpty(walletIso)) throw new IllegalArgumentException("No articleId or walletIso extra! " + walletIso); WebSettings webSettings = webView.getSettings(); if (0 != (getActivity().getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE)) { WebView.setWebContentsDebuggingEnabled(true); } webSettings.setDomStorageEnabled(true); webSettings.setJavaScriptEnabled(true); if (articleId != null && !articleId.isEmpty()) theUrl = theUrl + "/article?slug=" + articleId + "&currency=" + walletIso.toLowerCase(); Log.d(TAG, "onCreate: theUrl: " + theUrl + ", articleId: " + articleId); webView.loadUrl(theUrl); return rootView; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final ViewTreeObserver observer = signalLayout.getViewTreeObserver(); observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { observer.removeGlobalOnLayoutListener(this); BRAnimator.animateBackgroundDim(backgroundLayout, false); BRAnimator.animateSignalSlide(signalLayout, false, new BRAnimator.OnSlideAnimationEnd() { @Override public void onAnimationEnd() { } }); } }); } @Override public void onStop() { super.onStop(); BRAnimator.animateBackgroundDim(backgroundLayout, true); BRAnimator.animateSignalSlide(signalLayout, true, new BRAnimator.OnSlideAnimationEnd() { @Override public void onAnimationEnd() { if (getActivity() != null) { try { getActivity().getFragmentManager().popBackStack(); } catch (Exception ignored) { } } } }); } private class BRWebChromeClient extends WebChromeClient { @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { Log.e(TAG, "onConsoleMessage: consoleMessage: " + consoleMessage.message()); return super.onConsoleMessage(consoleMessage); } @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Log.e(TAG, "onJsAlert: " + message + ", url: " + url); return super.onJsAlert(view, url, message, result); } } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); Utils.hideKeyboard(getActivity()); BRAnimator.supportIsShowing = false; } }
package com.example.admnistrator.bookcrossingapp; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; import com.yzq.zxinglibrary.android.CaptureActivity; import com.yzq.zxinglibrary.bean.ZxingConfig; import com.yzq.zxinglibrary.common.Constant; public class MeFragment extends Fragment { public static final String ARGUMENT = "MeFragment"; private String mArgument; private View view; private Button btnPosing; private Button btnSwaping; private Button btnReviews; private Button btnRecords; private Button btnSetting; private Button btnWanting; //private FriendAdapter adapter; //private List<Friend> friendList = new ArrayList<>(); private int REQUEST_CODE_SCAN = 111; private int RESULT_OK = 1; public MeFragment(){ super(); //initMe(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view = inflater.inflate(R.layout.fragment_me, container, false); //initMeRecyclerView(); initButton(); return view; } private void initButton() { btnPosing = view.findViewById(R.id.me_button_posing); btnSwaping = view.findViewById(R.id.me_button_swaping); btnReviews = view.findViewById(R.id.me_button_reviews); btnRecords = view.findViewById(R.id.me_button_records); btnSetting = view.findViewById(R.id.me_button_settings); btnWanting = view.findViewById(R.id.me_button_wanting); btnPosing.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { /*ZxingConfig * * true * */ ZxingConfig config = new ZxingConfig(); config.setShowbottomLayout(true); config.setPlayBeep(true); config.setShake(true); config.setShowAlbum(true); config.setShowFlashLight(true); // ZxingConfig Intent intent = new Intent(getActivity(), CaptureActivity.class); intent.putExtra(Constant.INTENT_ZXING_CONFIG, config); startActivityForResult(intent, REQUEST_CODE_SCAN); } }); } public static MeFragment newInstance(String from) { Bundle bundle = new Bundle(); bundle.putString(ARGUMENT, from); MeFragment meFragment = new MeFragment(); meFragment.setArguments(bundle); return meFragment; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_SCAN && resultCode == -1) { if (data != null) { String content = data.getStringExtra(Constant.CODED_CONTENT); Toast.makeText(getActivity(), "" + content, Toast.LENGTH_SHORT).show(); } } } // private void initMe(){ // for (int i = 0; i < 3; i++){ // Friend friend1 = new Friend(R.drawable.friend_list_icon, "Yvettemuki"); // friendList.add(friend1); // Friend friend2 = new Friend(R.drawable.friend_list_icon,"Angelababy"); // public void initFriendsRecyclerView(){ // RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.friend_list_recyclerView); // LinearLayoutManager LayoutManager = new LinearLayoutManager(getContext()); // recyclerView.setLayoutManager(LayoutManager); // adapter = new FriendAdapter(friendList); // recyclerView.setAdapter(adapter); }
package com.example.mirnabouchra.cloudolympics; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.media.Image; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import android.widget.TextView.OnEditorActionListener; import android.view.inputmethod.EditorInfo; import com.example.mirnabouchra.cloudolympics.games.BlankGameActivity; import com.google.android.gms.common.ConnectionResult; import android.content.IntentSender.SendIntentException; import com.google.android.gms.common.api.GoogleApiClient; import com.firebase.client.Firebase; import com.google.android.gms.plus.Plus; import com.google.android.gms.plus.model.people.Person; import java.io.InputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Random; public class MainActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private static final String LOG_TAG = MainActivity.class.getSimpleName(); class DownloadImageAsyncTask extends AsyncTask<Uri, Void, Bitmap> { private Uri uri; @Override protected Bitmap doInBackground(Uri... params) { uri = params[0]; // URI scheme must be 'https' (for downloaded images), 'content' (for shared images), or // 'file' (for camera images). if (!(uri.getScheme().equals("https") || uri.getScheme().equals("content") || uri.getScheme().equals("file"))) { return null; } try { return BitmapUtils.decodeBitmapBounded( BitmapUtils.getInputStream(MainActivity.this, uri), 90, 90); } catch (IOException e) { Log.e(LOG_TAG, "Error reading bitmap", e); } return null; } @Override protected void onPostExecute(Bitmap result) { if (result != null) { BitmapDrawable bitmap = new BitmapDrawable(result); userImage.setImageDrawable(new RoundedAvatarDrawable(result)); } } } private ImageView userImage; private TextView username; private EditText code; private Firebase firebase; /* Request code used to invoke sign in user interactions. */ private static final int RC_SIGN_IN = 0; /* Client used to interact with Google APIs. */ private GoogleApiClient mGoogleApiClient; /* A flag indicating that a PendingIntent is in progress and prevents * us from starting further intents. */ private boolean mIntentInProgress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Firebase.setAndroidContext(this); setContentView(R.layout.activity_main); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Plus.API) .addScope(Plus.SCOPE_PLUS_LOGIN) .build(); firebase = new Firebase("https://cloud-olympics.firebaseio.com/"); username = (TextView) findViewById(R.id.username); userImage = (ImageView) findViewById(R.id.user_image); code = (EditText) findViewById(R.id.code); code.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { join(); return true; } }); code.requestFocus(); } @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); } protected void onStart() { Log.d(LOG_TAG, "onStart"); super.onStart(); mGoogleApiClient.connect(); } protected void onStop() { super.onStop(); if (mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } } public void join() { Intent intent = new Intent(this, BlankGameActivity.class); String codeValue = code.getText().toString(); String playerName; String imageUrl; if(mGoogleApiClient.isConnected()) { // Get data of current signed-in user Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient); playerName = currentPerson.getName().getGivenName(); imageUrl = getUserImageUrl(currentPerson); } else { Random rand = new Random(); playerName = "Anonymous " + rand.nextInt(10); imageUrl = ""; } // Register player data in Firebase Firebase ref = firebase.child("room/" + codeValue + "/players"); Firebase pushRef = ref.push(); Map<String, Object> user = new HashMap<String, Object>(); user.put("name", playerName); user.put("imageUrl", imageUrl); user.put("score", 0); pushRef.setValue(user); String key = pushRef.getKey(); // Add intent data intent.putExtra("playerId", key); intent.putExtra("playerName", playerName); intent.putExtra("code", codeValue); // Start the intent startActivity(intent); } private String getUserImageUrl(Person person) { String imageUrl = person.getImage().getUrl(); // re-create the image URL with a larger size String sizeSplit = "sz="; String[] parts = imageUrl.split(sizeSplit); imageUrl = parts[0] + sizeSplit + "500"; return imageUrl; } public void onConnectionFailed(ConnectionResult result) { if (!mIntentInProgress && result.hasResolution()) { try { mIntentInProgress = true; startIntentSenderForResult(result.getResolution().getIntentSender(), RC_SIGN_IN, null, 0, 0, 0); } catch (SendIntentException e) { // The intent was canceled before it was sent. Return to the default // state and attempt to connect to get an updated ConnectionResult. mIntentInProgress = false; mGoogleApiClient.connect(); } } } protected void onActivityResult(int requestCode, int responseCode, Intent intent) { if (requestCode == RC_SIGN_IN) { mIntentInProgress = false; if (!mGoogleApiClient.isConnecting()) { mGoogleApiClient.connect(); } } } public void onConnected(Bundle connectionHint) { Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient); Toast.makeText(this, "Welcome, " + currentPerson.getName().getGivenName() + "!", Toast.LENGTH_LONG).show(); username.setText(currentPerson.getName().getGivenName()); new DownloadImageAsyncTask().execute(Uri.parse(getUserImageUrl(currentPerson))); code.requestFocus(); } public void onConnectionSuspended(int cause) { mGoogleApiClient.connect(); } }
package com.example.youngki.memory_project; import android.app.Activity; import android.content.SharedPreferences; import android.gesture.Gesture; import android.gesture.GestureLibraries; import android.gesture.GestureLibrary; import android.gesture.GestureOverlayView; import android.gesture.Prediction; import android.media.MediaPlayer; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import android.gesture.GestureOverlayView.OnGesturePerformedListener; import com.google.gson.Gson; public class handWritingTrain extends Activity { GestureLibrary gestureLibrary = null; GestureOverlayView gestureOverlayView; TextView gestureResult; TextView textView2; TextView textView4; int cnt=0; HashMap<String, Integer> memMap = new HashMap<>(); Map<Integer, String> myNewHashMap = new HashMap<>(); String[] keys; Integer[] values; ArrayList<Integer> keyList = new ArrayList<>(); ArrayList<String> valueList = new ArrayList<>(); int[] audio = new int[] { R.raw.zero, R.raw.one, R.raw.two, R.raw.three, R.raw.four, R.raw.five, R.raw.six, R.raw.seven, R.raw.eight, R.raw.nine }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { Gson gson = new Gson(); SharedPreferences prefs = getSharedPreferences("MyPref", MODE_PRIVATE); String wrapperStr = prefs.getString("memMap", null); MapWrapper wrapper = gson.fromJson(wrapperStr, MapWrapper.class); this.keys = wrapper.getKeys(); this.values = wrapper.getValues(keys); super.onCreate(savedInstanceState); setContentView(R.layout.activity_hand_writing_train); generateHashMap(memMap, keys,values); keyList.addAll(myNewHashMap.keySet()); valueList.addAll(myNewHashMap.values()); textView2 = (TextView)findViewById(R.id.textView2); textView2.setText("The first one of map : "+myNewHashMap.get(keyList.get(0))+", write "+keyList.get(0)); textView4 = (TextView)findViewById(R.id.textView4); gestureResult = (TextView)findViewById(R.id.gestureresult); gestureOverlayView = (GestureOverlayView)findViewById(R.id.gestures); gestureLibrary = GestureLibraries.fromRawResource(this, R.raw.gestures); gestureLibrary.load(); gestureOverlayView.addOnGesturePerformedListener(gesturePerformedListener); } private void generateHashMap(HashMap<String, Integer> memMap, String[] keys, Integer[] values) { int i; for(i=0;i<keys.length;i++){ memMap.put(keys[i],values[i]); } //making into <Integer,String> for(Map.Entry<String, Integer> entry : memMap.entrySet()){ myNewHashMap.put(entry.getValue(), entry.getKey()); } } GestureOverlayView.OnGesturePerformedListener gesturePerformedListener = new GestureOverlayView.OnGesturePerformedListener(){ @Override public void onGesturePerformed(GestureOverlayView view, Gesture gesture) { ArrayList<Prediction> prediction = gestureLibrary.recognize(gesture); String targetString = new String(); String nextTargetString = new String(); String getString= new String(); int getInt; if(prediction.size() > 0){ if(cnt==memMap.size()) cnt = 0; targetString = myNewHashMap.get(keyList.get(cnt)); if(cnt==keyList.size()-1)cnt=-1; nextTargetString = myNewHashMap.get(keyList.get(cnt+1)); gestureResult.setText(prediction.get(0).name); getString = gestureResult.getText().toString(); gestureResult.setAlpha(0.0f);//1.0f to make it visible getInt = makeIntValue(getString); MediaPlayer.create(handWritingTrain.this,audio[memMap.get(targetString)]).start(); textView2.setText(keyList.toString()); textView2.setText("NEXT : "+nextTargetString+" is "+memMap.get(nextTargetString)+". Write "+memMap.get(nextTargetString)); cnt++; } }}; private int makeIntValue(String getString) { switch (getString) { case "zero" : return 0; case "one" : return 1; case "two" : return 2; case "three" : return 3; case "four" : return 4; case "five" : return 5; case "six" : return 6; case "seven" : return 7; case "eight" : return 8; case "nine" : return 9; default : return -1; } } }
package com.felix.zhiban.presenter.book; import android.content.Context; import com.felix.zhiban.base.BasePresenter; import com.felix.zhiban.bean.book.BookRoot; import com.felix.zhiban.model.book.DoubanBookModel; import com.felix.zhiban.modelinterface.book.IDoubanBookModel; import com.felix.zhiban.presenterinterface.book.IDoubanBookPresenter; import com.felix.zhiban.viewinterface.book.ISearchBookByTagView; public class DouBanBookPresenter extends BasePresenter implements IDoubanBookPresenter { private ISearchBookByTagView iSearchBookByTagView; private IDoubanBookModel iDoubanBookModel; public DouBanBookPresenter(Context mContext, ISearchBookByTagView iSearchBookByTagView) { super(mContext); this.iSearchBookByTagView = iSearchBookByTagView; this.iDoubanBookModel = new DoubanBookModel(mContext, this); } @Override public void searchBookByTag(String tag, boolean isLoadMore) { iDoubanBookModel.initBookByTag(tag, isLoadMore); } @Override public void searchBookByTagSuccess(BookRoot bookRoot, boolean isLoadMore) { iSearchBookByTagView.showBooksContentView(); iSearchBookByTagView.SearchBookByTagSuccess(bookRoot, isLoadMore); } @Override public void searchBookByTagFail() { //iSearchBookByTagView.SearchBookByTagFail(); iSearchBookByTagView.showBooksError(); } }
package com.github.jmuthu.poovali.activity; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.TimePickerDialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.Spinner; import android.widget.SpinnerAdapter; import android.widget.TextView; import android.widget.TimePicker; import com.github.jmuthu.poovali.R; import com.github.jmuthu.poovali.model.BatchContent; import com.github.jmuthu.poovali.model.EventContent; import com.github.jmuthu.poovali.model.PlantContent; import com.github.jmuthu.poovali.utility.Helper; import com.github.jmuthu.poovali.utility.MyExceptionHandler; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.UUID; public class AddEventActivity extends AppCompatActivity { static boolean isSowActivity = true; EventContent.Event mEvent = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this)); String plantId = null; String batchId = null; Bundle extras = getIntent().getExtras(); if (extras != null) { isSowActivity = extras.getBoolean(Helper.ARG_IS_SOW_ACTIVITY); batchId = extras.getString(Helper.ARG_BATCH_ID); String eventId = extras.getString(Helper.ARG_EVENT_ID); plantId = extras.getString(Helper.ARG_PLANT_ID); if (eventId != null) { mEvent = EventContent.getEvent(eventId); } } setContentView(R.layout.activity_add_event); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); Spinner eventSpinner = (Spinner) findViewById(R.id.event_type_spinner); String label; SpinnerAdapter plantSpinnerAdapter; Spinner plantSpinner = (Spinner) findViewById(R.id.plant_type_spinner); Date date = Calendar.getInstance().getTime(); String description = null; if (isSowActivity) { findViewById(R.id.event_type_label).setVisibility(View.GONE); eventSpinner.setVisibility(View.GONE); label = getResources().getString(R.string.plant_label); plantSpinnerAdapter = new CustomSpinnerAdapter<PlantContent.Plant>(this, PlantContent.getItems()); plantSpinner.setAdapter(plantSpinnerAdapter); if (plantId != null) { plantSpinner.setSelection(PlantContent.getItems() .indexOf(PlantContent.getPlant(plantId))); plantSpinner.setEnabled(false); } } else { EventContent.BatchActivityEvent.Type[] batchActivityList = EventContent.BatchActivityEvent.Type.values(); SpinnerAdapter eventSpinnerAdapter = new EventTypeSpinnerAdapter(this, batchActivityList); eventSpinner.setAdapter(eventSpinnerAdapter); label = getResources().getString(R.string.batch_label); List<BatchContent.Batch> batchList = BatchContent.getBatchList(); plantSpinnerAdapter = new CustomSpinnerAdapter<BatchContent.Batch>(this, batchList); plantSpinner.setAdapter(plantSpinnerAdapter); if (batchId != null) { plantSpinner.setSelection(batchList.indexOf(BatchContent.getBatch(batchId))); plantSpinner.setEnabled(false); } if (mEvent != null) { date = mEvent.getCreatedDate(); eventSpinner.setSelection( ((EventContent.BatchActivityEvent) mEvent).getType().ordinal()); eventSpinner.setEnabled(false); description = mEvent.getDescription(); } } TextView plant_label = (TextView) findViewById(R.id.plant_label); plant_label.setText(label); TextView dateView = (TextView) findViewById(R.id.date); dateView.setText(Helper.DATE_FORMAT.format(date)); TextView timeView = (TextView) findViewById(R.id.time); timeView.setText(Helper.TIME_FORMAT.format(date)); TextView eventDescription = (TextView) findViewById(R.id.event_description); eventDescription.setText(description); } public void saveEvent(View v) { TextView dateView = (TextView) findViewById(R.id.date); TextView timeView = (TextView) findViewById(R.id.time); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT); String dateString = dateView.getText().toString() + " " + timeView.getText().toString(); Date date; try { date = df.parse(dateString); } catch (ParseException e) { Log.e(this.getClass().getName(), "Unable to parse date : " + dateString, e); AlertDialog.Builder builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert); builder.setMessage("Invalid date, try again!"); builder.setTitle("Save failed"); builder.setPositiveButton(android.R.string.ok, null); builder.show(); return; } if (!validateDate(date)) { return; } Spinner spinner = (Spinner) findViewById(R.id.plant_type_spinner); Spinner eventTypeSpinner = (Spinner) findViewById(R.id.event_type_spinner); EditText desc = (EditText) findViewById(R.id.event_description); if (mEvent == null) { mEvent = EventContent.createEvent(isSowActivity); } mEvent.setCreatedDate(date); mEvent.setDescription(desc.getText().toString()); BatchContent.Batch batch; if (isSowActivity) { batch = new BatchContent.Batch(); batch.setId(UUID.randomUUID().toString()); batch.setDescription(desc.getText().toString()); batch.setCreatedDate(date); PlantContent.Plant plant = (PlantContent.Plant) spinner.getSelectedItem(); batch.setPlant(plant); SimpleDateFormat format = new SimpleDateFormat("dd MMM yy"); batch.setName(batch.getPlant().getName() + " - " + format.format(batch.getCreatedDate())); plant.addBatch(this, batch); } else { batch = (BatchContent.Batch) spinner.getSelectedItem(); ((EventContent.BatchActivityEvent) mEvent). setType((EventContent.BatchActivityEvent.Type) eventTypeSpinner.getSelectedItem()); } batch.addEvent(this, mEvent); finish(); } public void cancelAddEvent(View v) { finish(); } public void showDatePickerDialog(View v) { DialogFragment newFragment = new DatePickerFragment(); newFragment.show(getSupportFragmentManager(), "datePicker"); } public void showTimePickerDialog(View v) { DialogFragment newFragment = new TimePickerFragment(); newFragment.show(getSupportFragmentManager(), "timePicker"); } public boolean validateDate(Date date) { if (isSowActivity) { Spinner spinner = (Spinner) findViewById(R.id.plant_type_spinner); PlantContent.Plant plant = (PlantContent.Plant) spinner.getSelectedItem(); if (plant.isDuplicateBatch(date)) { AlertDialog.Builder builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert); builder.setMessage("Batch already exists for the given date, select another date!"); builder.setTitle("Save failed"); builder.setPositiveButton(android.R.string.ok, null); builder.show(); return false; } } return true; } public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @Override @NonNull public Dialog onCreateDialog(Bundle savedInstanceState) { TextView dateView = (TextView) getActivity().findViewById(R.id.date); Calendar calendar = Calendar.getInstance(); Long now = calendar.getTimeInMillis(); try { calendar.setTime(Helper.DATE_FORMAT.parse(dateView.getText().toString())); } catch (ParseException e) { Log.e(this.getClass().getName(), "Unable to parse date : " + dateView.getText(), e); return new DatePickerDialog(getActivity(), this, 2016, 1, 1); } int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day); if (!isSowActivity) { Spinner spinner = (Spinner) getActivity().findViewById(R.id.plant_type_spinner); BatchContent.Batch batch = (BatchContent.Batch) spinner.getSelectedItem(); if (batch.getCreatedDate() != null) { dialog.getDatePicker().setMinDate(batch.getCreatedDate().getTime()); } } dialog.getDatePicker().setMaxDate(now); return dialog; } public void onDateSet(DatePicker view, int year, int month, int day) { TextView dateView = (TextView) getActivity().findViewById(R.id.date); Calendar calendar = Calendar.getInstance(); calendar.set(year, month, day); dateView.setText(Helper.DATE_FORMAT.format(calendar.getTime())); } } public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener { @Override @NonNull public Dialog onCreateDialog(@NonNull Bundle savedInstanceState) { TextView timeView = (TextView) getActivity().findViewById(R.id.time); Calendar calendar = Calendar.getInstance(); try { calendar.setTime(Helper.TIME_FORMAT.parse(timeView.getText().toString())); } catch (ParseException e) { Log.e(this.getClass().getName(), "Unable to parse time : " + timeView.getText(), e); return new TimePickerDialog(getActivity(), this, 0, 0, false); } int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); return new TimePickerDialog(getActivity(), this, hour, minute, android.text.format.DateFormat.is24HourFormat(getActivity())); } public void onTimeSet(TimePicker view, int hourOfDay, int minute) { TextView dateView = (TextView) getActivity().findViewById(R.id.time); final Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR, hourOfDay); calendar.set(Calendar.MINUTE, minute); dateView.setText(Helper.TIME_FORMAT.format(calendar.getTime())); } } public class EventTypeSpinnerAdapter extends ArrayAdapter<EventContent.BatchActivityEvent.Type> { EventTypeSpinnerAdapter(Activity context, EventContent.BatchActivityEvent.Type[] list) { super(context, 0, list); } @NonNull public View getView(int position, View convertView, @NonNull ViewGroup parent) { EventContent.BatchActivityEvent.Type item = getItem(position); if (convertView == null) { convertView = LayoutInflater.from(getContext()) .inflate(R.layout.spinner_item, parent, false); } if (item != null) { ImageView imageView = (ImageView) convertView.findViewById(R.id.img); imageView.setImageResource(getResources().getIdentifier( Helper.getImageFileName(item.toString()), "drawable", imageView.getContext().getPackageName())); TextView textView = (TextView) convertView.findViewById(R.id.txt); textView.setText(item.toString()); } return convertView; } public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) { return getView(position, convertView, parent); } } public class CustomSpinnerAdapter<T extends Helper.DisplayableItem> extends ArrayAdapter<T> { CustomSpinnerAdapter(Activity context, List<T> list) { super(context, 0, list); } @NonNull public View getView(int position, View convertView, @NonNull ViewGroup parent) { T item = getItem(position); if (convertView == null) { convertView = LayoutInflater.from(getContext()) .inflate(R.layout.spinner_item, parent, false); } if (item != null) { ImageView imageView = (ImageView) convertView.findViewById(R.id.img); imageView.setImageResource(getResources().getIdentifier( item.getImageName(), "drawable", imageView.getContext().getPackageName())); TextView textView = (TextView) convertView.findViewById(R.id.txt); textView.setText(item.getName()); } return convertView; } public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) { return getView(position, convertView, parent); } } }
package com.performancetweaker.app.utils; import com.asksven.android.common.utils.SystemAppInstaller; import com.stericson.RootTools.RootTools; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Build; import android.util.Log; import java.util.ArrayList; public class SystemAppUtilities { private static final String SYSTEM_DIR_4_4 = "/system/priv-app/"; private static final String SYSTEM_DIR = "/system/app/"; private static String getAPKName(Context ctx, boolean includeFullPath, boolean doWildCard) throws com.performancetweaker.app.utils.SystemAppManagementException { String fullPath = ctx.getApplicationInfo().sourceDir; if (fullPath.isEmpty() || (fullPath.lastIndexOf('/') == -1)) { throw new com.performancetweaker.app.utils.SystemAppManagementException( "Unable to find the path to the APK. Is it already uninstalled? Did you remember to reboot after uninstalling? Current location appears to be: " + fullPath); } if (!includeFullPath) { fullPath = fullPath.substring(fullPath.lastIndexOf('/') + 1); } if (doWildCard) { int indexOfHyphen = fullPath.lastIndexOf('-'); if (indexOfHyphen > 0) { return fullPath.substring(0, indexOfHyphen) + "*"; } } return fullPath; } public static void installAsSystemApp(final Context ctx) throws SystemAppManagementException { AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() { SystemAppManagementException error = null; ProgressDialog progress = null; @Override protected void onPreExecute() { super.onPreExecute(); progress = ProgressDialog.show(ctx, "Please Wait", "Copying App to System"); } @Override protected Boolean doInBackground(Void... params) { // Verify we do have root if (!RootTools.isAccessGiven()) { return false; } // Copy the file to /system/priv-app String currentFile; try { currentFile = getAPKName(ctx, true, false); } catch (SystemAppManagementException e) { error = e; return false; } boolean copiedApp = installAsSystemApp(currentFile); Log.d(Constants.App_Tag, "Copying app to system directory" + ". Was it successful? " + copiedApp); if (!copiedApp) { error = new SystemAppManagementException("Unable to copy the file \"" + currentFile + "\" to \"" + "\". You may need to try this manually using a tool such as Root Explorer."); return false; } //TODO install backup script on cm based roms //installBackupScript(ctxt); return true; } @Override protected void onPostExecute(Boolean result) { progress.dismiss(); if (result) { AlertDialog.Builder builder = new AlertDialog.Builder(ctx); builder.setMessage("Reboot to Apply Changes") .setTitle("Complete") .setNeutralButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { rebootDevice(((Dialog) dialog).getContext()); } }) .setNegativeButton("No", null) .show(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(ctx); String message = (error != null) ? error.getMessage() : "Unknown Error"; builder.setMessage(message).setNeutralButton(android.R.string.ok, null).show(); } } }; task.execute(); } private static void rebootDevice(final Context context) { AsyncTask<Void, Void, Boolean> rebootTask = new AsyncTask<Void, Void, Boolean>() { ProgressDialog progressDialog; @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = ProgressDialog.show(context, "Rebooting", "Please Wait"); } @Override protected Boolean doInBackground(Void... voids) { ArrayList<String> rebootCommand = new ArrayList<>(); rebootCommand.add("reboot"); SysUtils.executeRootCommand(rebootCommand); return null; } @Override protected void onPostExecute(Boolean status) { super.onPostExecute(status); progressDialog.dismiss(); if (!status) { Log.d(Constants.App_Tag, "Restarting phone via rootTools as reboot failed..."); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage("Unable to reboot automatically . Please reboot your phone manually.") .setNeutralButton(android.R.string.ok, null) .show(); } } }; rebootTask.execute(); } private static boolean installAsSystemApp(String apk) { ArrayList<String> command = new ArrayList<>(); command.add("mount -o rw,remount /system"); if (Build.VERSION.SDK_INT >= 19) { command.add("cp " + apk + " " + SYSTEM_DIR_4_4 + "performancetweaker.apk"); command.add("chmod 644 " + SYSTEM_DIR_4_4 + "performancetweaker.apk"); } else { command.add("cp " + apk + " " + SYSTEM_DIR + "performancetweaker.apk"); command.add("chmod 644 "+ SYSTEM_DIR+ "performancetweaker.apk"); } return SysUtils.executeRootCommand(command); } }
package com.pr0gramm.app.util.decoders; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapRegionDecoder; import android.graphics.Point; import android.graphics.Rect; import android.net.Uri; import com.davemorrissey.labs.subscaleview.decoder.ImageRegionDecoder; import java.io.FileInputStream; import static com.pr0gramm.app.util.AndroidUtility.toFile; /** * Default decoder using android region decoder. */ public class AndroidRegionDecoder implements ImageRegionDecoder { private BitmapRegionDecoder decoder; private Bitmap.Config config; public AndroidRegionDecoder(Bitmap.Config config) { this.config = config; } @SuppressLint("NewApi") @Override public Point init(Context context, Uri uri) throws Exception { if (!"file".equals(uri.getScheme())) throw new IllegalArgumentException("Must be a file:// uri"); try (FileInputStream input = new FileInputStream(toFile(uri))) { decoder = BitmapRegionDecoder.newInstance(input.getFD(), false); } return new Point(decoder.getWidth(), decoder.getHeight()); } @Override public Bitmap decodeRegion(Rect rect, int sampleSize) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = config; options.inSampleSize = sampleSize; return decoder.decodeRegion(rect, options); } @Override public boolean isReady() { return decoder != null && !decoder.isRecycled(); } @Override public void recycle() { if (decoder != null) { decoder.recycle(); } } }
package derpibooru.derpy.ui.fragments; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import butterknife.Bind; import butterknife.ButterKnife; import derpibooru.derpy.R; import derpibooru.derpy.data.server.DerpibooruSearchOptions; import derpibooru.derpy.ui.views.FloatingSearchView; public class BrowseOptionsFragment extends Fragment { @Bind(R.id.floatingSearchView) FloatingSearchView searchText; @Bind(R.id.spinnerSortBy) Spinner sortBy; @Bind(R.id.spinnerSortDirection) Spinner sortDirection; @Bind(R.id.spinnerFavesFilter) Spinner favesFilter; @Bind(R.id.spinnerUpvotesFilter) Spinner upvotesFilter; @Bind(R.id.spinnerUploadsFilter) Spinner uploadsFilter; @Bind(R.id.spinnerWatchedTagsFilter) Spinner watchedTagsFilter; @Bind(R.id.textMinScore) EditText minScore; @Bind(R.id.textMaxScore) EditText maxScore; private DerpibooruSearchOptions mSelectedOptions = new DerpibooruSearchOptions(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_browse_options, container, false); ButterKnife.bind(this, v); if ((savedInstanceState != null) && (savedInstanceState.containsKey(BrowseFragment.EXTRAS_SEARCH_OPTIONS))) { mSelectedOptions = savedInstanceState.getParcelable(BrowseFragment.EXTRAS_SEARCH_OPTIONS); } else { mSelectedOptions = getArguments().getParcelable(BrowseFragment.EXTRAS_SEARCH_OPTIONS); } setSearchActionListenerForSearchQueryView(); setSpinnerState(mSelectedOptions); return v; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(BrowseFragment.EXTRAS_SEARCH_OPTIONS, getSelectedOptions()); } public DerpibooruSearchOptions getSelectedOptions() { if (searchText != null) { hideSoftKeyboard(); mSelectedOptions.setSearchQuery( searchText.getText().toString().isEmpty() ? "*" : searchText.getText().toString()); mSelectedOptions.setSortBy( DerpibooruSearchOptions.SortBy.fromValue(sortBy.getSelectedItemPosition())); mSelectedOptions.setSortDirection( DerpibooruSearchOptions.SortDirection.fromValue(sortDirection.getSelectedItemPosition())); mSelectedOptions.setFavesFilter( DerpibooruSearchOptions.UserPicksFilter.fromValue(favesFilter.getSelectedItemPosition())); mSelectedOptions.setUpvotesFilter( DerpibooruSearchOptions.UserPicksFilter.fromValue(upvotesFilter.getSelectedItemPosition())); mSelectedOptions.setUploadsFilter( DerpibooruSearchOptions.UserPicksFilter.fromValue(uploadsFilter.getSelectedItemPosition())); mSelectedOptions.setWatchedTagsFilter( DerpibooruSearchOptions.UserPicksFilter.fromValue(watchedTagsFilter.getSelectedItemPosition())); mSelectedOptions.setMinScore( getInteger(minScore.getText().toString())); mSelectedOptions.setMaxScore( getInteger(maxScore.getText().toString())); } return mSelectedOptions; } private void setSpinnerState(DerpibooruSearchOptions from) { if (!from.getSearchQuery().equals("*")) searchText.setText(from.getSearchQuery()); sortBy.setSelection(from.getSortBy().toValue()); sortDirection.setSelection(from.getSortDirection().toValue()); favesFilter.setSelection(from.getFavesFilter().toValue()); upvotesFilter.setSelection(from.getUpvotesFilter().toValue()); uploadsFilter.setSelection(from.getUploadsFilter().toValue()); watchedTagsFilter.setSelection(from.getWatchedTagsFilter().toValue()); if (from.getMinScore() != null) minScore.setText(from.getMinScore().toString()); if (from.getMaxScore() != null) maxScore.setText(from.getMaxScore().toString()); } private Integer getInteger(String text) { return (text.equals("")) ? null : Integer.parseInt(text); } private void setSearchActionListenerForSearchQueryView() { /* TODO: start search on keyboard search button press */ searchText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { hideSoftKeyboard(); return true; } return false; } }); } private void hideSoftKeyboard() { InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(searchText.getWindowToken(), 0); } }
package guishinti.unicesumarpresencial; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.Spinner; import org.apache.http.client.methods.HttpGet; public class LaboratoriosActivity extends AppCompatActivity { RelativeLayout rl_telaLoading; RelativeLayout rl_telaErro; ProgressBar progressBar; Button bt_refresh; Spinner sp_turno; ListView lv_labs; String turnoParam = ""; Boolean sp_status = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_laboratorios); rl_telaLoading = (RelativeLayout) findViewById(R.id.rl_telaLoading); rl_telaErro = (RelativeLayout) findViewById(R.id.rl_telaErro); progressBar = (ProgressBar) findViewById(R.id.pb_loading); bt_refresh = (Button) findViewById(R.id.bt_refresh); bt_refresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loading(); } }); sp_turno = (Spinner) findViewById(R.id.sp_turno); lv_labs = (ListView) findViewById(R.id.lv_labs); Turno.populaSpinner(sp_turno,this); Turno.getPeriodo(sp_turno); sp_turno.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (sp_status == true) { sp_status = false; turnoParam = Turno.getParamTurnos(sp_turno.getSelectedItemPosition()); loading(); } } @Override public void onNothingSelected(AdapterView<?> parent) {} }); loading(); } public void loading(){ if (Conexao.verificaConexao(this)){ Lab.array.clear(); lv_labs.setVisibility(View.INVISIBLE); rl_telaErro.setVisibility(View.INVISIBLE); rl_telaLoading.setVisibility(View.VISIBLE); new AsyncDataClass().execute(); }else{ error(); } } public void error(){ lv_labs.setVisibility(View.INVISIBLE); rl_telaLoading.setVisibility(View.INVISIBLE); rl_telaErro.setVisibility(View.VISIBLE); } private class AsyncDataClass extends AsyncTask<String, Void, String> { Pagina html; Conexao con = new Conexao(); private String host = "http: private String labs = "/informaticav2/horario.php?dados="; @Override protected String doInBackground(String... params) { System.out.println(host+labs+Turno.getDiaAtual()+turnoParam); HttpGet url= new HttpGet(host+labs+Turno.getDiaAtual()+turnoParam); html = new Pagina(con.get(url,"UTF-8")); return html.toString(); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); System.out.println("Resulted Value: " + result); if(result.equals("") || result == null){ sp_status = true; System.out.println("Server connection failed"); error(); }else{ sp_status = true; PaginaLab.getPaginaLabs(); Lab.setList(LaboratoriosActivity.this,lv_labs); rl_telaLoading.setVisibility(View.INVISIBLE); rl_telaErro.setVisibility(View.INVISIBLE); lv_labs.setVisibility(View.VISIBLE); } } } }
package org.openlmis.core.view.activity; import android.app.FragmentManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.InputFilter; import android.text.TextUtils; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import org.openlmis.core.R; import org.openlmis.core.model.RnRForm; import org.openlmis.core.presenter.Presenter; import org.openlmis.core.presenter.RequisitionPresenter; import org.openlmis.core.utils.ToastUtil; import org.openlmis.core.view.adapter.RequisitionFormAdapter; import org.openlmis.core.view.fragment.OnBackConfirmDialog; import org.openlmis.core.view.fragment.RetainedFragment; import org.openlmis.core.view.viewmodel.RnRFormViewModel; import org.openlmis.core.view.widget.InputFilterMinMax; import roboguice.RoboGuice; import roboguice.inject.ContentView; import roboguice.inject.InjectView; @ContentView(R.layout.activity_requisition) public class RequisitionActivity extends BaseActivity implements RequisitionPresenter.RequisitionView, View.OnClickListener { @InjectView(R.id.requisition_form) ListView requisitionForm; @InjectView(R.id.product_name_list_view) ListView requisitionNameList; @InjectView(R.id.btn_complete) private Button btnComplete; @InjectView(R.id.btn_save) private View btnSave; @InjectView(R.id.action_panel) private View actionPanel; @InjectView(R.id.vg_container) private ViewGroup vgContainer; @InjectView(R.id.edit_text) private EditText etConsultationNumbers; LayoutInflater inflater; RequisitionPresenter presenter; Boolean hasDataChanged; private RetainedFragment dataFragment; @InjectView(R.id.requisition_header_right) View bodyHeaderView; @InjectView(R.id.requisition_header_left) View productHeaderView; @InjectView(R.id.tv_label_request) TextView headerRequestAmount; @InjectView(R.id.tv_label_approve) TextView headerApproveAmount; RequisitionFormAdapter productListAdapter; RequisitionFormAdapter requisitionFormAdapter; private boolean consultationNumbersHasChanged; private boolean isHistoryForm; private void initPresenter() { // find the retained fragment on activity restarts FragmentManager fm = getFragmentManager(); dataFragment = (RetainedFragment) fm.findFragmentByTag("RetainedFragment"); if (dataFragment == null) { dataFragment = new RetainedFragment(); fm.beginTransaction().add(dataFragment, "RetainedFragment").commit(); presenter = RoboGuice.getInjector(getApplicationContext()).getInstance(RequisitionPresenter.class); dataFragment.putData("presenter", presenter); } else { presenter = (RequisitionPresenter) dataFragment.getData("presenter"); } } @Override public boolean onCreateOptionsMenu(Menu menu) { return false; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); long formId = getIntent().getLongExtra("formId", 0); isHistoryForm = formId != 0; inflater = LayoutInflater.from(this); hasDataChanged = (Boolean) dataFragment.getData("hasDataChanged"); initUI(); presenter.loadRequisitionFormList(formId); } @Override public void refreshRequisitionForm() { setEditable(); productListAdapter.notifyDataSetChanged(); requisitionFormAdapter.notifyDataSetChanged(); setConsultationNumbers(); } @Override public void highLightApprovedAmount() { headerRequestAmount.setBackgroundResource(android.R.color.transparent); headerRequestAmount.setTextColor(getResources().getColor(R.color.primary_text)); headerApproveAmount.setBackgroundResource(R.color.color_accent); headerApproveAmount.setTextColor(getResources().getColor(R.color.white)); requisitionFormAdapter.setStatus(RnRForm.STATUS.SUBMITTED); } @Override public void highLightRequestAmount() { headerRequestAmount.setBackgroundResource(R.color.color_accent); headerRequestAmount.setTextColor(getResources().getColor(R.color.white)); headerApproveAmount.setBackgroundResource(android.R.color.transparent); headerApproveAmount.setTextColor(getResources().getColor(R.color.primary_text)); requisitionFormAdapter.setStatus(RnRForm.STATUS.DRAFT); } private void setEditable() { if (presenter.formIsEditable()) { vgContainer.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); actionPanel.setVisibility(View.VISIBLE); } else { vgContainer.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); actionPanel.setVisibility(View.GONE); setTitle(new RnRFormViewModel(presenter.getRnRForm()).getPeriod()); } } private void setConsultationNumbers() { etConsultationNumbers.setText(presenter.getConsultationNumbers()); etConsultationNumbers.post(new Runnable() { @Override public void run() { etConsultationNumbers.addTextChangedListener(etConsultationNumbersTextWatcher); } }); } @Override public void showErrorMessage(String msg) { ToastUtil.show(msg); } @Override public Presenter getPresenter() { initPresenter(); return presenter; } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_save: onSaveBtnClick(); break; case R.id.btn_complete: onProcessButtonClick(); break; default: break; } } @Override public void showListInputError(int index) { final int position = index; requisitionForm.setSelection(position); requisitionForm.post(new Runnable() { @Override public void run() { View childAt = getViewByPosition(position, requisitionForm); final EditText viewById = (EditText) childAt.findViewById(R.id.et_request_amount); viewById.requestFocus(); viewById.setError(getString(R.string.hint_error_input)); } }); } @Override protected void onDestroy() { dataFragment.putData("presenter", presenter); if (hasDataChanged()) { dataFragment.putData("hasDataChanged", hasDataChanged()); } super.onDestroy(); } private void initUI() { initRequisitionBodyList(); initRequisitionProductList(); requisitionNameList.post(new Runnable() { @Override public void run() { productHeaderView.getLayoutParams().height = bodyHeaderView.getHeight(); } }); setListViewOnTouchAndScrollListener(requisitionForm, requisitionNameList); btnComplete.setText(getResources().getString(R.string.btn_submit)); btnComplete.setOnClickListener(this); btnSave.setOnClickListener(this); etConsultationNumbers.setFilters(new InputFilter[]{new InputFilterMinMax(Integer.MAX_VALUE)}); etConsultationNumbers.addTextChangedListener(etConsultationNumbersTextWatcher); } private void initRequisitionBodyList() { requisitionFormAdapter = new RequisitionFormAdapter(this, presenter.getRequisitionViewModelList(), false); requisitionForm.setAdapter(requisitionFormAdapter); } private void initRequisitionProductList() { productListAdapter = new RequisitionFormAdapter(this, presenter.getRequisitionViewModelList(), true); requisitionNameList.setAdapter(productListAdapter); } @Override public void setProcessButtonName(String name) { btnComplete.setText(name); } private void onProcessButtonClick() { String consultationNumbers = etConsultationNumbers.getText().toString(); if (TextUtils.isEmpty(consultationNumbers)) { etConsultationNumbers.setError(getString(R.string.hint_error_input)); return; } presenter.processRequisition(consultationNumbers); } @Override public void completeSuccess() { ToastUtil.showForLongTime(R.string.msg_requisition_submit_tip); goToHomePage(); } public View getViewByPosition(int pos, ListView listView) { final int firstListItemPosition = listView.getFirstVisiblePosition(); final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1; if (pos < firstListItemPosition || pos > lastListItemPosition) { return listView.getAdapter().getView(pos, null, listView); } else { final int childIndex = pos - firstListItemPosition; return listView.getChildAt(childIndex); } } private void onSaveBtnClick() { presenter.saveRequisition(etConsultationNumbers.getText().toString()); } private class MyScrollListener implements AbsListView.OnScrollListener { ListView list1; ListView list2; public MyScrollListener(ListView list1, ListView list2) { this.list1 = list1; this.list2 = list2; } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == 0 || scrollState == 1) { View subView1 = view.getChildAt(0); if (subView1 != null) { final int top1 = subView1.getTop(); View subview2 = list2.getChildAt(0); if (subview2 != null) { int top2 = subview2.getTop(); int position = view.getFirstVisiblePosition(); if (top1 != top2) { list2.setSelectionFromTop(position, top1); } } } } } public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { View subView1 = view.getChildAt(0); if (subView1 != null) { int top1 = subView1.getTop(); View subView2 = list2.getChildAt(0); if (subView2 != null) { int top2 = list2.getChildAt(0).getTop(); if (top1 != top2) { list1.setSelectionFromTop(firstVisibleItem, top1); list2.setSelectionFromTop(firstVisibleItem, top1); } } } } } private void setListViewOnTouchAndScrollListener(ListView listView1, ListView listView2) { listView2.setOnScrollListener(new MyScrollListener(listView2, listView1)); listView1.setOnScrollListener(new MyScrollListener(listView1, listView2)); } @Override public void goToHomePage() { Intent intent = new Intent(RequisitionActivity.this, HomeActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(HomeActivity.class, true); } private boolean hasDataChanged() { if (hasDataChanged == null) { hasDataChanged = requisitionFormAdapter.hasDataChanged() || consultationNumbersHasChanged; } return hasDataChanged; } TextWatcher etConsultationNumbersTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { String input = etConsultationNumbers.getText().toString(); if (!input.equals(presenter.getConsultationNumbers())) { consultationNumbersHasChanged = true; presenter.setConsultationNumbers(input); } } }; @Override public void onBackPressed() { if (hasDataChanged()) { OnBackConfirmDialog.showDialog(this, new OnBackConfirmDialog.ResultCallBack() { @Override public void callback(boolean flag) { if (flag) { removeTempForm(); finish(); } } }); } else { removeTempForm(); super.onBackPressed(); } } private void removeTempForm() { if (!isHistoryForm) { presenter.removeRnrForm(); } } public static Intent getIntentToMe(Context context, long formId) { Intent intent = new Intent(context, RequisitionActivity.class); intent.putExtra("formId", formId); return intent; } }
package mobi.cangol.mobile.security; import android.test.InstrumentationTestCase; public class AESUtilsTest extends InstrumentationTestCase { public void testEncrypt() throws Exception { String source="test"; String seed="12345678"; String dst=AESUtils.encrypt(seed, source); assertNotNull(dst); //assertEquals("73C58BAFE578C59366D8C995CD0B9D6D",dst); } public void testDecrypt() throws Exception { String source="73C58BAFE578C59366D8C995CD0B9D6D"; String seed="12345678"; //String dst=AESUtils.decrypt(seed, source); //assertNotNull(dst); //assertEquals("test",dst); //assertEquals(AESUtils.decrypt("12345678", AESUtils.encrypt("12345678", "test")), "test"); } }