answer
stringlengths
17
10.2M
package com.yagadi.enguage.expression.when; import java.util.ListIterator; import com.yagadi.enguage.sofa.Attributes; import com.yagadi.enguage.util.Audit; import com.yagadi.enguage.util.Strings; /* import java.util.ArrayList; class Strings extends ArrayList<String> { public Strings() {} public Strings( String s ) { int i=0; while( i<s.length()) { while (i<s.length() && s.charAt( i ) == ' ') i++; if (i<s.length()) { String tmp = ""; while (i<s.length() && s.charAt( i ) != ' ') tmp += s.charAt( i++ ); add( tmp ); } } } public Strings contract( String s ) { return this; } } // */ public class When { public static final String NAME = "when"; // types - used in constructing When (FROM implies TO also) public static final int AT = 0; // inital type - a moment public static final int FROM = 1; public static final int TO = 2; public static Audit audit = new Audit( NAME ); // general properties to help constuct Whens private static boolean future = false; private static boolean past = false; private static boolean present = true; public static void pastIs() { past = true; present = future = false; } public static void futureIs() { future = true; past = present = false; } public static void presentIs() { present = true; future = past = false; } public static boolean isPast() { return past; } public static boolean isFuture() { return future; } public static boolean isPresent() { return present; } //constructors public When() { scale( Time.DAY ); } public When( Moment m ) { this( m, m ); } public When( String s ) { // s = output from valueOf(), e.g. "19630818073088-20480905070088" Strings sa = new Strings( s, '-' ); // s.size() == 2 -> from/to int size = sa.size(); if (size==1) to = from = new Moment( sa.get( 0 )); else if (size == 2) { from = new Moment( sa.get( 0 )); to = new Moment( sa.get( 1 )); } } public When( Moment fr, Moment t ) { from = fr; to = t; } // from/to Attributes public When( Attributes a ) { this( a.get( "when" )); } public Attributes toAttributes() { return new Attributes().add( "when", valueOf());} // helper ("non-static factory") methods public When today() { audit.in( "today", "w="+ toString()); long today = (Moment.getNow().moment() / Time.DAY ); // * Moment.DAY; if (type == TO) to().date( today ); else from().date( today ); scale( Time.DAY ); audit.out( toString()); return this; } public When yesterday() { return today().prevDay();} public When tomorrow() { return today().nextDay();} public When thisWeek( String requiredDay ) { audit.in( "thisWeek", "w="+ toString() +", req="+ requiredDay ); today(); int actualDoW = type == TO ? Day.dayInWeek( Day.name( to().moment() )) : Day.dayInWeek( Day.name( from().moment() )); int reqireDoW = Day.dayInWeek( requiredDay ); dayShift( reqireDoW - actualDoW ); shift(); audit.out( toString()); return this; } // apply public When anniversary( int date ) { if (type==TO) to.anniversary( date ); else from.anniversary( date ); return this; } public When christmas() { return today().anniversary( 1225 ); } public When christmas( int year ) { return today().anniversary( year * 10000 + 1225 ); } // members private Moment now = Moment.getNow(); public long now() { return now.moment(); } private Moment from = new Moment(); public Moment from() { return from; } public When from( Moment m ) { from = m; type = FROM; return this; } private Moment to = from; public Moment to() { return to; } public When to( Moment m ) { to = m; type = TO; return this; } private int type = AT; // AT, AT->FROM, AT->TO, AT->FROM->TO, AT->TO->FROM. public int type() { return type; } public When type( int t ) { if (type==AT && (t==TO || t==FROM)) // split! to = new Moment( to ); type = t; return this; } private boolean absolute = true; public boolean isAbsolute() { return absolute; } public When absoluteIs( boolean b ) { absolute = b; return this;} public boolean isRelative() { return !absolute; } public When relativeIs( boolean b ) { absolute = !b; return this;} private boolean spurious = false; // 35th May -- a real date! public When spurious(boolean b) { spurious = b; return this; } public boolean spurious() {return spurious; } private boolean exact = false; // until seconds given or "precisely" or "exactly" public boolean isExact() { return exact; } public When exactIs( boolean b ) { exact = b; return this; } public long scale() { return type == TO ? to.scale() : from.scale(); } public When scale( long l ) { if (type == TO) to().scale( l ); else from().scale( l ); return this; } public static String scaleToString( long scale ) { if (scale == Time.YEAR) return "year"; else if (scale == Time.MONTH) return "month"; else if (scale == Time.DAY) return "day"; else if (scale == Time.HOUR) return "hour"; else if (scale == Time.MINUTE)return "minute"; else /* if (scale == S) */ return "second"; } /* ++++++++++++++++++++++++++++++++++++++++++++++++++ * shifting is a transformation on a time point to be * applied once the timepoint is determined. E.g. * "a week ago last Thursday" is * "a week ago" a -7 day shift on, wait for it, "last Thursday" */ private long dayShift = 0; public void dayShift( long l ) { audit.debug("ds="+l); dayShift += l; } private long monthShift = 0; public void monthShift( long l ) { audit.debug("ms="+l); monthShift += l;} private long yearShift = 0; public void yearShift( long l ) { audit.debug("ys="+l); yearShift += l; } public When shift() { audit.in( "shift", toString() +", y="+ yearShift +", m="+monthShift +", d="+ dayShift ); if (isUnassigned()) today(); // shift when... if (yearShift < 0) while ( yearShift++ != 0) prevYear(); else while ( yearShift-- != 0) nextYear(); if (monthShift < 0) while (monthShift++ != 0) prevMonth(); else while (monthShift-- != 0) nextMonth(); if (dayShift < 0) while ( dayShift++ != 0) prevDay(); else while ( dayShift-- != 0) nextDay(); // ... and, reset shifts dayShift = monthShift = yearShift = 0; audit.out( toString() ); return this; } // methods public void year( long y ) { if (type == TO) to().year( y ); else from().year( y );} public void month( int m ) { if (type == TO) to().month( m ); else from().month( m );} public void day( int d ) { if (type == TO) to().day( d ); else from().day( d );} public void hour( int h ) { if (type == TO) to().hour( h ); else from().hour( h );} public void minute(int m ) { if (type == TO) to().minute(m ); else from().minute(m );} public void second(int s ) { if (type == TO) to().second(s ); else from().second(s );} public long year( ) { return (type == TO)? to().year() : from().year(); } public int month( ) { return (type == TO)? to().month() : from().month(); } public int day( ) { return (type == TO)? to().day() : from().day(); } public int hour( ) { return (type == TO)? to().hour() : from().hour(); } public int minute() { return (type == TO)? to().minute() : from().minute();} public int second() { return (type == TO)? to().second() : from().second();} private When nextYear() {if (type==TO) to.nextYear(); else from.nextYear(); return this; } private When prevYear() {if (type==TO) to.prevYear(); else from.prevYear(); return this; } private When nextMonth(){if (type==TO) to.nextMonth();else from.nextMonth();return this; } private When prevMonth(){if (type==TO) to.prevMonth();else from.prevMonth();return this; } private When nextDay() {if (type==TO) to.nextDay(); else from.nextDay(); return this; } private When prevDay() {if (type==TO) to.prevDay(); else from.prevDay(); return this; } public boolean isUnassigned() {return from.isUnassigned() && to.isUnassigned();} public void unassign() { from.unassign(); to = from; type( AT ); } public When am() {if (type == TO) to().am( true ); else from().am( true ); return this;} public When pm() {if (type == TO) to().pm( true ); else from().pm( true ); return this; } public When time(long time ) {if (type == TO) to().time( time ); else from().time( time ); return this; } public long time() {return type == TO ? to.time() : from.time();} public When date( long d ) {if (type == TO) to().date( d ); else from().date( d ); return this; } public long date( int t ) {return t == TO ? to.time() : from.time();} public long date() {return type == TO ? to.time() : from.time();} boolean isDuration() { return (from != to) && !from.isUnassigned() && !to.isUnassigned(); } boolean isMoment() { return from == to; } // attributes -- as per Number.java public When representamen( String s ) { if (type == TO) to.representamen( s ); else from.representamen( s ); return this; } public When representamen( Strings s ) { if (type == TO) to.representamen( s ); else from.representamen( s ); return this; } public When representamenAppend( Strings s ) { if (type == TO) to.representamen().addAll( s ); else from.representamen().addAll( s ); return this; } public Strings representamen() {return type == TO ? to.representamen() : from.representamen();} // Let's call digital time "10:30" // represented as [ "10", ":", "30" ] // with an absolute value of 00000000103000 // so "today at 10:30" will be yyyymmdd103000 private String rep = ""; public String rep() { return rep; } public When rep( String s ) { rep = s; return this;} public String toString() { String rc = isMoment() ? from.toString( "" ) : toString( "from", "until" ); return rc.equals( "" ) ? rep() : rc; } public String toString( String fromPrefix, String toPrefix ) { String rc = ""; if (!from.isUnassigned()) rc += from.toString( fromPrefix ); if ( !to.isUnassigned()) rc += to.toString( toPrefix ); return rc.equals( "" ) ? rep() : rc; } public String valueOf() { String rc = from.valueOf(); if (from.moment() != to.moment()) rc += "-"+ to.valueOf(); return rc; } private static boolean interpret( When w, ListIterator<String> si ) { audit.in( "interpret", "" ); boolean rc = false; // if false the caller will rewind si w.type( AT ); if ((Strings.doString( "on", si ) && !(rc = Relative.doOn( w, si ))) || (Strings.doString( "at", si ) && !(rc = Time.doAt( w, si ))) || (Strings.doString( "in", si ) && !(rc = Relative.doIn( w, si ))) ) // do [month] year si.previous(); // replace "in", "at" or "on" if (Relative.doRelativeDay( w, si )) rc = true; // ignore failure, doRelativeDay() is a bonus! // not quite the same as above, or... "at Tuesday" would be fine! /* if ( (Strings.doString( "in", si ) * || Strings.doString( "on", si ) * || Strings.doString( "at", si )) * && !(rc = Moment.doMoment( w.type( AT ), si ))) * si.previous(); */ if ( (Strings.doString( "from", si ) || Strings.doString( "after", si )) && !(rc = Moment.doMoment( w.type( FROM ), si ))) si.previous(); // replace from/after if (( Strings.doString( "until", si ) || Strings.doString( "to", si ) || Strings.doString( "before", si )) && !(rc = Moment.doMoment( w.type( TO ), si ))) si.previous(); // replace until/to return audit.out( rc ); } public static When getWhen( Strings sa ) { return getWhen( new When(), sa ); } public static When getWhen( When w, Strings sa ) { if (sa != null) { Audit.suspend(); w.type( AT ); int start = 0; boolean found = false; ListIterator<String> si = sa.listIterator(); while (!found && si.hasNext()) { start = si.nextIndex(); found = When.interpret( w, si ); if (!found && si.hasNext()) si.next(); } if (found) w.shift().representamen( sa.remove( start, si.nextIndex() - start )); else w.unassign(); Audit.resume(); } return w; } // -- test code private static void testGet( String s ) { testGet( s, s ); } // default to true private static void testGet( String request, String result ) { Strings sa = new Strings( request ); When w = When.getWhen( new When(), sa ); if (w == null) audit.FATAL( "w is null!" ); else { String ws = w.toString(); boolean shouldBeAssigned = !request.equals( result ); audit.log( "'"+ request +"' means"+ (!w.isUnassigned() || shouldBeAssigned? ":" : " just that!") ); if (!w.isUnassigned() || shouldBeAssigned) audit.log( "'"+ (result.equals("") ? sa.toString( Strings.SPACED ):result) +"' (when="+ ws +")" ); if (shouldBeAssigned && w.isUnassigned()) audit.FATAL( "w is unassigned!! >"+ w.toString() +"<" ); if (!shouldBeAssigned && !w.isUnassigned()) audit.FATAL( "w is assigned!" ); if (!result.equals("") && !result.equals( sa.toString( Strings.SPACED ))) audit.FATAL( "wrong answer: "+ sa.toString( Strings.SPACED ) +"!" ); audit.log( "" ); } } public static void main( String args[]) { When w = new When( Moment.getNow()); audit.log( "Now is "+ w.toString()); audit.log( "Today is "+ w.today().toString()); audit.log( "Wednesday is "+ w.thisWeek( Day.WED ).toString()); audit.log( "how long is it to xmas? "+ new Duration( new When().now(), w.christmas().from().moment() ).toString()); audit.log( "Christmas day is on a "+w. christmas().from.dayName()); // was at testGet( "now i am meeting my brother" ); int test = 0; if (test==1 || test==0) { // a from/until/on the DATE|DAY [at TIME] audit.log( "test 1 ********************" ); testGet( "i was born on the sabbath" ); Audit.allOn(); Audit.traceAll( true ); //Audit.allOff(); Audit.traceAll( false ); testGet( "i was born on the 18th of August 1964", "i was born" ); testGet( "i was born on the 18th of August 1964 at 10:30am", "i was born" ); testGet( "i met my brother on holiday" ); testGet( "I am meeting emily at 7:30", "I am meeting emily"); testGet( "I am meeting james tomorrow at 7:30", "I am meeting james"); testGet( "i met my brother on Thursday", "i met my brother" ); testGet( "i met my brother on Thursday at 6pm", "i met my brother" ); audit.log( "test 1 passes!" ); } if (test == 2 || test == 0) { audit.log("test 2 ********** this,next,last **********"); testGet( "i am meeting my brother for the last time", "i am meeting my brother for the last time" ); testGet( "i am meeting my brother last Thursday", "i am meeting my brother" ); testGet( "i am meeting my brother this way" ); testGet( "i am meeting my brother this Thursday", "i am meeting my brother" ); testGet( "i am meeting my brother next time" ); testGet( "i am meeting my brother next Thursday", "i am meeting my brother" ); audit.log( "test 2 passes!" ); } if (test == 3 || test == 0) { audit.log("test 3 ********** yesterday, today, tomorrow **********"); testGet( "i met my brother yesterday", "i met my brother" ); testGet( "i am meeting my brother today", "i am meeting my brother" ); testGet( "i am reading today's menu" ); testGet( "i am meeting my brother tomorrow", "i am meeting my brother" ); audit.log( "test 3 passes!" ); } if (test == 4 || test == 0) { audit.log( "test 4 ********** a week ago **********" ); testGet( "i met my brother a week ago last way" ); testGet( "i met my brother a week ago last Thursday", "i met my brother" ); testGet( "i am meeting my brother a week ago", "i am meeting my brother" ); testGet( "i am meeting my brother a week ago last Thursday", "i am meeting my brother" ); testGet( "i am meeting my brother a week last Thursday", "i am meeting my brother" ); testGet( "I met my brother 2 months ago at the pub", "I met my brother at the pub" ); testGet( "I met my brother 2 months ago yesterday at the pub", "I met my brother at the pub" ); testGet( "I met my brother a year ago tomorrow at the pub", "I met my brother at the pub" ); audit.log( "test 4 passes!" ); } if (test == 5 || test == 0) { audit.log("test 5 ********* until ***********"); //Audit.allOn(); Audit.traceAll( true ); testGet( "I am with my brother until 7:30pm tomorrow at the pub", "I am with my brother at the pub" ); testGet( "we are going to from Wednesday until today", "we are going to" ); testGet( "we are going to from Wednesday until last night", "we are going to" ); testGet( "we are going to from Wednesday until Thursday", "we are going to" ); testGet( "we are going to from Wednesday until the 11th of February 2016", "we are going to" ); testGet( "we are going to from Wednesday until Thursday the 11th of February 2016", "we are going to" ); testGet( "Queen Elizabeth I reigned from 1558 to 1603", "Queen Elizabeth I reigned"); testGet( "we are going to from 1558 to 1603", "we are going to"); audit.log( "test 5 passes!" ); } if (test == 6 || test == 0) { audit.log("test 6 ********* simple tense context ***********"); audit.log( "setting past" ); When.pastIs(); testGet( "i met my brother on Thursday", "i met my brother" ); audit.log( "setting present" ); When.presentIs(); testGet( "i am meeting my brother on Thursday", "i am meeting my brother" ); audit.log( "setting future" ); When.futureIs(); testGet( "i am meeting my brother on Thursday", "i am meeting my brother" ); audit.log( "test 6 passes!" ); } audit.log( ">>>:"+ new When().rep( "idk" ).toString() +":" ); /* testGet( "i am meeting my brother now", null, "a moment in time" ); // don't check time - it changes! testGet( "i am meeting my brother today", "today", "a day" ); testGet( "i am meeting my brother tomorrow", "tomorrow", "a day" ); testGet( "i am meeting my brother yesterday", "yesterday", "a day" ); testGet( "i am meeting my brother at 5pm", "at 5 pm", "a moment in time" ); testGet( "i am meeting my brother at 7:30", "at 7 30", "a moment in time" ); testGet( "i am meeting my brother at 7:30 pm", "at 7 30 pm", "a moment in time" ); testGet( "i am meeting my brother at 7:30 am", "at 7 30 am", "a moment in time" ); testGet( "i am meeting my brother 7:30:42", "at 7 30 and 42 seconds", "a moment in time" ); testGet( "i am meeting my brother on Thursday", null, "a day" ); // this is probably wrong - d/t is not known testGet( "i am meeting my brother next Thursday", null, "a day" ); // this is probably wrong - d/t is not known // --*/ //testGet( "i met my brother at 5pm", null, "a moment in time" ); // this is probably wrong - d/t is not known // -- testGet( "a week ago last Thursday" ); // -- testGet( "a week tomorrow" ); //w = When.day( new Strings( "1225" )); //if (null != w) // audit.audit( "Day of week is "+ Moment.dayOfWeek( w.from())); //w = When.day( new Strings( "the 25th December" )); //if (null != w) // audit.audit( "Day of week is "+ When.Moment.dayOfWeek( w.from())); //testGet( "I'm meeting my brother at 7:30 at the pub", "at 7 30", "a moment in time" ); //audit.audit( new When( Long.valueOf( 73000 ) ).toString()); } }
package org.opennms.netmgt.statsd.jmx; import org.opennms.netmgt.dao.db.AbstractTransactionalTemporaryDatabaseSpringContextTests; import org.opennms.test.DaoTestConfigBean; /** * @author <a href="mailto:dj@opennms.org">DJ Gregor</a> */ public class StatsdTest extends AbstractTransactionalTemporaryDatabaseSpringContextTests { @Override protected void setUpConfiguration() throws Exception { DaoTestConfigBean daoTestConfig = new DaoTestConfigBean(); daoTestConfig.afterPropertiesSet(); } @Override protected String[] getConfigLocations() { return new String[] { "classpath:META-INF/opennms/applicationContext-daemon.xml", "classpath:META-INF/opennms/mockEventIpcManager.xml" }; } public void testInitStartStop() throws Exception { Statsd mbean = new Statsd(); mbean.init(); mbean.start(); Thread.sleep(2000); mbean.stop(); } // due to bugs introduced by the refreshing behavior of appContexts... // this will have to this well have to wait until we implement osgi public void FIXMEtestInitStartStopTwice() throws Exception { Statsd mbean = new Statsd(); mbean.init(); mbean.start(); mbean.stop(); mbean.init(); mbean.start(); mbean.stop(); } }
package org.opennms.netmgt.trapd; import java.io.StringReader; import java.net.InetAddress; import junit.framework.TestCase; import junit.framework.TestSuite; import org.opennms.netmgt.EventConstants; import org.opennms.netmgt.eventd.EventConfigurationManager; import org.opennms.netmgt.mock.EventAnticipator; import org.opennms.netmgt.mock.MockEventIpcManager; import org.opennms.netmgt.mock.MockTrapdConfig; import org.opennms.netmgt.snmp.PropertySettingTestSuite; import org.opennms.netmgt.snmp.SnmpInstId; import org.opennms.netmgt.snmp.SnmpObjId; import org.opennms.netmgt.snmp.SnmpTrapBuilder; import org.opennms.netmgt.snmp.SnmpUtils; import org.opennms.netmgt.snmp.SnmpV1TrapBuilder; import org.opennms.netmgt.xml.event.Event; import org.opennms.test.mock.MockLogAppender; public class TrapHandlerTest extends TestCase { public static TestSuite suite() { Class testClass = TrapHandlerTest.class; TestSuite suite = new TestSuite(testClass.getName()); suite.addTest(new PropertySettingTestSuite(testClass, "JoeSnmp Tests", "org.opennms.snmp.strategyClass", "org.opennms.netmgt.snmp.joesnmp.JoeSnmpStrategy")); suite.addTest(new PropertySettingTestSuite(testClass, "Snmp4J Tests", "org.opennms.snmp.strategyClass", "org.opennms.netmgt.snmp.snmp4j.Snmp4JStrategy")); return suite; } private TrapHandler m_trapHandler = null; private EventAnticipator m_anticipator = null; private MockEventIpcManager m_eventMgr = null; private InetAddress m_localhost = null; private int m_port = 10000; private static final String m_ip = "127.0.0.1"; private static final long m_nodeId = 1; protected void setUp() throws Exception { MockLogAppender.setupLogging(); m_anticipator = new EventAnticipator(); m_eventMgr = new MockEventIpcManager(); m_eventMgr.setEventAnticipator(m_anticipator); m_localhost = InetAddress.getByName(m_ip); String eventconf = "<events xmlns=\"http://xmlns.opennms.org/xsd/eventconf\">\n" + " <global>\n" + " <security>\n" + " <doNotOverride>logmsg</doNotOverride>\n" + " <doNotOverride>operaction</doNotOverride>\n" + " <doNotOverride>autoaction</doNotOverride>\n" + " <doNotOverride>tticket</doNotOverride>\n" + " <doNotOverride>script</doNotOverride>\n" + " </security>\n" + " </global>\n" + "\n" + " <event>\n" + " <mask>\n" + " <maskelement>\n" + " <mename>id</mename>\n" + " <mevalue>.1.3.6.1.2.1.15.7</mevalue>\n" + " </maskelement>\n" + " <maskelement>\n" + " <mename>generic</mename>\n" + " <mevalue>6</mevalue>\n" + " </maskelement>\n" + " <maskelement>\n" + " <mename>specific</mename>\n" + " <mevalue>1</mevalue>\n" + " </maskelement>\n" + " </mask>\n" + " <uei>uei.opennms.org/IETF/BGP/traps/bgpEstablished</uei>\n" + " <event-label>BGP4-MIB defined trap event: bgpEstablished</event-label>\n" + " <descr>&lt;p&gt;The BGP Established event is generated when\n" + " the BGP FSM enters the ESTABLISHED state.&lt;/p&gt;&lt;table&gt;\n" + " &lt;tr&gt;&lt;td&gt;&lt;b&gt;\n" + " bgpPeerLastError&lt;/b&gt;&lt;/td&gt;&lt;td&gt;%parm[ " &lt;/td&gt;&lt;td&gt;&lt;p;&gt;&lt;/p&gt;&lt;/td;&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;b&gt;\n" + " bgpPeerState&lt;/b&gt;&lt;/td&gt;&lt;td&gt;%parm[ " &lt;/td&gt;&lt;td&gt;&lt;p;&gt;\n" + " idle(1) connect(2) active(3) opensent(4) openconfirm(5) established(6)&lt;/p&gt;\n" + " &lt;/td;&gt;&lt;/tr&gt;&lt;/table&gt;\n" + " </descr>\n" + " <logmsg dest='logndisplay'>&lt;p&gt;BGP Event: FSM entered connected state.&lt;/p&gt;</logmsg>\n" + " <severity>Normal</severity>\n" + " </event>\n" + "\n" + " <event>\n" + " <mask>\n" + " <maskelement>\n" + " <mename>id</mename>\n" + " <mevalue>.1.3.6.1.2.1.15.7</mevalue>\n" + " </maskelement>\n" + " <maskelement>\n" + " <mename>generic</mename>\n" + " <mevalue>6</mevalue>\n" + " </maskelement>\n" + " <maskelement>\n" + " <mename>specific</mename>\n" + " <mevalue>2</mevalue>\n" + " </maskelement>\n" + " </mask>\n" + " <uei>uei.opennms.org/IETF/BGP/traps/bgpBackwardTransition</uei>\n" + " <event-label>BGP4-MIB defined trap event: bgpBackwardTransition</event-label>\n" + " <descr>&lt;p&gt;The BGPBackwardTransition Event is generated\n" + " when the BGP FSM moves from a higher numbered\n" + " state to a lower numbered state.&lt;/p&gt;&lt;table&gt;\n" + " &lt;tr&gt;&lt;td&gt;&lt;b&gt;\n" + " bgpPeerLastError&lt;/b&gt;&lt;/td&gt;&lt;td&gt;%parm[ " &lt;/td&gt;&lt;td&gt;&lt;p;&gt;&lt;/p&gt;&lt;/td;&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;b&gt;\n" + " bgpPeerState&lt;/b&gt;&lt;/td&gt;&lt;td&gt;%parm[ " &lt;/td&gt;&lt;td&gt;&lt;p;&gt;\n" + " idle(1) connect(2) active(3) opensent(4) openconfirm(5) established(6)&lt;/p&gt;\n" + " &lt;/td;&gt;&lt;/tr&gt;&lt;/table&gt;\n" + " </descr>\n" + " <logmsg dest='discardtraps'>&lt;p&gt;BGP Event: FSM Backward Transistion.&lt;/p&gt;</logmsg>\n" + " <severity>Warning</severity>\n" + " </event>\n" + "\n" + " <event>\n" + " <mask>\n" + " <maskelement>\n" + " <mename>generic</mename>\n" + " <mevalue>0</mevalue>\n" + " </maskelement>\n" + " </mask>\n" + " <uei>uei.opennms.org/generic/traps/SNMP_Cold_Start</uei>\n" + " <event-label>OpenNMS-defined trap event: SNMP_Cold_Start</event-label>\n" + " <descr>\n" + " &lt;p&gt;A coldStart trap signifies that the sending\n" + " protocol entity is reinitializing itself such that the\n" + " agent's configuration or the protocol entity implementation\n" + " may be altered.&lt;/p&gt;\n" + " </descr>\n" + " <logmsg dest='logndisplay'>\n" + " Agent Up with Possible Changes (coldStart Trap)\n" + " enterprise:%id% (%id%) args(%parm[##]%):%parm[all]%\n" + " </logmsg>\n" + " <severity>Normal</severity>\n" + " </event>\n" + "</events>"; StringReader reader = new StringReader(eventconf); EventConfigurationManager.loadConfiguration(reader); TrapdIPMgr.clearKnownIpsMap(); TrapdIPMgr.setNodeId(m_ip, m_nodeId); } protected void setUpTrapHandler(boolean newSuspectOnTrap) { MockTrapdConfig mockTrapdConfig = new MockTrapdConfig(); mockTrapdConfig.setSnmpTrapPort(m_port); mockTrapdConfig.setNewSuspectOnTrap(newSuspectOnTrap); m_trapHandler = new TrapHandler(); m_trapHandler.setTrapdConfig(mockTrapdConfig); m_trapHandler.setEventManager(m_eventMgr); m_trapHandler.init(); m_trapHandler.start(); } public void finishUp() { try { Thread.sleep(1000); } catch (InterruptedException e) { // do nothing } m_eventMgr.finishProcessingEvents(); m_anticipator.verifyAnticipated(1000, 0, 0, 0, 0); } public void tearDown() { if (m_trapHandler != null) { m_trapHandler.stop(); m_trapHandler = null; } } public void testV1TrapNoNewSuspect() throws Exception { TrapdIPMgr.clearKnownIpsMap(); anticipateAndSend(false, false, "uei.opennms.org/default/trap", "v1", null, 6, 1); } public void testV2TrapNoNewSuspect() throws Exception { TrapdIPMgr.clearKnownIpsMap(); anticipateAndSend(false, false, "uei.opennms.org/default/trap", "v2c", null, 6, 1); } public void testV1TrapNewSuspect() throws Exception { TrapdIPMgr.clearKnownIpsMap(); anticipateAndSend(true, false, "uei.opennms.org/default/trap", "v1", null, 6, 1); } public void testV2TrapNewSuspect() throws Exception { TrapdIPMgr.clearKnownIpsMap(); anticipateAndSend(true, false, "uei.opennms.org/default/trap", "v2c", null, 6, 1); } public void testV1EnterpriseIdAndGenericMatch() throws Exception { anticipateAndSend(false, true, "uei.opennms.org/IETF/BGP/traps/bgpEstablished", "v1", ".1.3.6.1.2.1.15.7", 6, 1); } public void testV2EnterpriseIdAndGenericAndSpecificMatch() throws Exception { anticipateAndSend(false, true, "uei.opennms.org/IETF/BGP/traps/bgpEstablished", "v2c", ".1.3.6.1.2.1.15.7", 6, 1); } public void testV2EnterpriseIdAndGenericAndSpecificMatchWithZero() throws Exception { anticipateAndSend(false, true, "uei.opennms.org/IETF/BGP/traps/bgpEstablished", "v2c", ".1.3.6.1.2.1.15.7.0", 6, 1); } public void testV2EnterpriseIdAndGenericAndSpecificMissWithExtraZeros() throws Exception { anticipateAndSend(false, true, "uei.opennms.org/default/trap", "v2c", ".1.3.6.1.2.1.15.7.0.0", 6, 1); } public void testV1EnterpriseIdAndGenericAndSpecificMissWithWrongGeneric() throws Exception { anticipateAndSend(false, true, "uei.opennms.org/default/trap", "v1", ".1.3.6.1.2.1.15.7", 5, 1); } public void testV1EnterpriseIdAndGenericAndSpecificMissWithWrongSpecific() throws Exception { anticipateAndSend(false, true, "uei.opennms.org/default/trap", "v1", ".1.3.6.1.2.1.15.7", 6, 50); } public void testV1GenericMatch() throws Exception { anticipateAndSend(false, true, "uei.opennms.org/generic/traps/SNMP_Cold_Start", "v1", null, 0, 0); } public void testV2GenericMatch() throws Exception { anticipateAndSend(false, true, "uei.opennms.org/generic/traps/SNMP_Cold_Start", "v2c", ".1.3.6.1.6.3.1.1.5.1", 0, 0); } public void testV1TrapDroppedEvent() throws Exception { anticipateAndSend(false, true, null, "v1", ".1.3.6.1.2.1.15.7", 6, 2); } public void testV2TrapDroppedEvent() throws Exception { anticipateAndSend(false, true, null, "v2c", ".1.3.6.1.2.1.15.7", 6, 2); } public void testV1TrapDefaultEvent() throws Exception { anticipateAndSend(false, true, "uei.opennms.org/default/trap", "v1", null, 6, 1); } public void testV2TrapDefaultEvent() throws Exception { anticipateAndSend(false, true, "uei.opennms.org/default/trap", "v2c", null, 6, 1); } public void testNodeGainedModifiesIpMgr() throws Exception { long nodeId = 2; setUpTrapHandler(true); anticipateEvent("uei.opennms.org/default/trap", m_ip, nodeId); Event event = anticipateEvent(EventConstants.NODE_GAINED_INTERFACE_EVENT_UEI, m_ip, nodeId); m_eventMgr.sendNow(event); try { Thread.sleep(100); } catch (InterruptedException e) { // do nothing } sendTrap("v1", null, 6, 1); finishUp(); } public void testInterfaceReparentedModifiesIpMgr() throws Exception { long nodeId = 2; setUpTrapHandler(true); anticipateEvent("uei.opennms.org/default/trap", m_ip, nodeId); Event event = anticipateEvent(EventConstants.INTERFACE_REPARENTED_EVENT_UEI, m_ip, nodeId); m_eventMgr.sendNow(event); try { Thread.sleep(100); } catch (InterruptedException e) { // do nothing } sendTrap("v1", null, 6, 1); finishUp(); } public void testInterfaceDeletedModifiesIpMgr() throws Exception { long nodeId = 0; setUpTrapHandler(true); anticipateEvent("uei.opennms.org/default/trap", m_ip, nodeId); Event event = anticipateEvent(EventConstants.INTERFACE_DELETED_EVENT_UEI, m_ip, nodeId); m_eventMgr.sendNow(event); anticipateEvent("uei.opennms.org/internal/discovery/newSuspect", m_ip, nodeId); try { Thread.sleep(100); } catch (InterruptedException e) { // do nothing } sendTrap("v1", null, 6, 1); finishUp(); } public Event anticipateEvent(String uei) { return anticipateEvent(uei, m_ip, m_nodeId); } public Event anticipateEvent(String uei, String ip, long nodeId) { Event event = new Event(); event.setInterface(ip); event.setNodeid(nodeId); event.setUei(uei); m_anticipator.anticipateEvent(event); return event; } public void anticipateAndSend(boolean newSuspectOnTrap, boolean nodeKnown, String event, String version, String enterprise, int generic, int specific) throws Exception { setUpTrapHandler(newSuspectOnTrap); if (newSuspectOnTrap) { // Note: the nodeId will be zero because the node is not known anticipateEvent("uei.opennms.org/internal/discovery/newSuspect", m_ip, 0); } if (event != null) { if (nodeKnown) { anticipateEvent(event); } else { /* * If the node is unknown, the nodeId on the trap event * will be zero. */ anticipateEvent(event, m_ip, 0); } } sendTrap(version, enterprise, generic, specific); finishUp(); } public void sendTrap(String version, String enterprise, int generic, int specific) throws Exception { if (enterprise == null) { enterprise = ".0.0"; } if (version.equals("v1")) { sendV1Trap(enterprise, generic, specific); } else if (version.equals("v2c")) { sendV2Trap(enterprise, specific); } else { throw new Exception("unsupported SNMP version for test: " + version); } } public void sendV1Trap(String enterprise, int generic, int specific) throws Exception { SnmpV1TrapBuilder pdu = SnmpUtils.getV1TrapBuilder(); pdu.setEnterprise(SnmpObjId.get(enterprise)); pdu.setGeneric(generic); pdu.setSpecific(specific); pdu.setTimeStamp(0); pdu.setAgentAddress(m_localhost); pdu.send(m_localhost.getHostAddress(), m_port, "public"); } public void sendV2Trap(String enterprise, int specific) throws Exception { SnmpObjId enterpriseId = SnmpObjId.get(enterprise); boolean isGeneric = false; SnmpObjId trapOID; if (SnmpObjId.get(".1.3.6.1.6.3.1.1.5").isPrefixOf(enterpriseId)) { isGeneric = true; trapOID = enterpriseId; } else { trapOID = SnmpObjId.get(enterpriseId, new SnmpInstId(specific)); // XXX or should it be this // trap OID = enterprise + ".0." + specific; } SnmpTrapBuilder pdu = SnmpUtils.getV2TrapBuilder(); pdu.addVarBind(SnmpObjId.get(".1.3.6.1.2.1.1.3.0"), SnmpUtils.getValueFactory().getTimeTicks(0)); pdu.addVarBind(SnmpObjId.get(".1.3.6.1.6.3.1.1.4.1.0"), SnmpUtils.getValueFactory().getObjectId(trapOID)); if (isGeneric) { pdu.addVarBind(SnmpObjId.get(".1.3.6.1.6.3.1.1.4.3.0"), SnmpUtils.getValueFactory().getObjectId(enterpriseId)); } pdu.send(m_localhost.getHostAddress(), m_port, "public"); } }
package org.eclipse.mylyn.tasks.ui; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ISaveContext; import org.eclipse.core.resources.ISaveParticipant; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Preferences.IPropertyChangeListener; import org.eclipse.core.runtime.Preferences.PropertyChangeEvent; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.text.hyperlink.IHyperlinkDetector; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.mylyn.context.core.ContextCorePlugin; import org.eclipse.mylyn.internal.context.core.ContextPreferenceContstants; import org.eclipse.mylyn.internal.tasks.core.LocalRepositoryConnector; import org.eclipse.mylyn.internal.tasks.core.ScheduledTaskContainer; import org.eclipse.mylyn.internal.tasks.core.TaskDataManager; import org.eclipse.mylyn.internal.tasks.ui.IDynamicSubMenuContributor; import org.eclipse.mylyn.internal.tasks.ui.ITaskHighlighter; import org.eclipse.mylyn.internal.tasks.ui.ITaskListNotification; import org.eclipse.mylyn.internal.tasks.ui.ITaskListNotificationProvider; import org.eclipse.mylyn.internal.tasks.ui.ITasksUiConstants; import org.eclipse.mylyn.internal.tasks.ui.OfflineCachingStorage; import org.eclipse.mylyn.internal.tasks.ui.OfflineFileStorage; import org.eclipse.mylyn.internal.tasks.ui.RepositoryAwareStatusHandler; import org.eclipse.mylyn.internal.tasks.ui.TaskListBackupManager; import org.eclipse.mylyn.internal.tasks.ui.TaskListColorsAndFonts; import org.eclipse.mylyn.internal.tasks.ui.TaskListNotificationIncoming; import org.eclipse.mylyn.internal.tasks.ui.TaskListNotificationManager; import org.eclipse.mylyn.internal.tasks.ui.TaskListNotificationQueryIncoming; import org.eclipse.mylyn.internal.tasks.ui.TaskListNotificationReminder; import org.eclipse.mylyn.internal.tasks.ui.TaskListSynchronizationScheduler; import org.eclipse.mylyn.internal.tasks.ui.TasksUiPreferenceConstants; import org.eclipse.mylyn.internal.tasks.ui.util.TaskListSaveManager; import org.eclipse.mylyn.internal.tasks.ui.util.TaskListWriter; import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiExtensionReader; import org.eclipse.mylyn.internal.tasks.ui.views.TaskListView; import org.eclipse.mylyn.internal.tasks.ui.views.TaskRepositoriesView; import org.eclipse.mylyn.internal.tasks.ui.wizards.EditRepositoryWizard; import org.eclipse.mylyn.monitor.core.StatusHandler; import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector; import org.eclipse.mylyn.tasks.core.AbstractRepositoryQuery; import org.eclipse.mylyn.tasks.core.AbstractTask; import org.eclipse.mylyn.tasks.core.AbstractTaskDataHandler; import org.eclipse.mylyn.tasks.core.ITaskActivityListener; import org.eclipse.mylyn.tasks.core.RepositoryTaskAttribute; import org.eclipse.mylyn.tasks.core.RepositoryTaskData; import org.eclipse.mylyn.tasks.core.RepositoryTemplate; import org.eclipse.mylyn.tasks.core.TaskComment; import org.eclipse.mylyn.tasks.core.TaskRepository; import org.eclipse.mylyn.tasks.core.TaskRepositoryManager; import org.eclipse.mylyn.tasks.core.AbstractTask.PriorityLevel; import org.eclipse.mylyn.tasks.core.AbstractTask.RepositoryTaskSyncState; import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorFactory; import org.eclipse.mylyn.web.core.WebClientUtil; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IStartup; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** * Main entry point for the Tasks UI. * * @author Mik Kersten * @since 2.0 */ public class TasksUiPlugin extends AbstractUIPlugin implements IStartup { public static final String LABEL_VIEW_REPOSITORIES = "Task Repositories view"; public static final String ID_PLUGIN = "org.eclipse.mylyn.tasks.ui"; private static final String FOLDER_OFFLINE = "offline"; private static final String DIRECTORY_METADATA = ".metadata"; private static final String NAME_DATA_DIR = ".mylyn"; private static final char DEFAULT_PATH_SEPARATOR = '/'; private static final int NOTIFICATION_DELAY = 5000; private static TasksUiPlugin INSTANCE; private static TaskListManager taskListManager; private static TaskRepositoryManager taskRepositoryManager; private static TaskListSynchronizationScheduler synchronizationScheduler; private static RepositorySynchronizationManager synchronizationManager; private static Map<String, AbstractRepositoryConnectorUi> repositoryConnectorUiMap = new HashMap<String, AbstractRepositoryConnectorUi>(); private TaskListSaveManager taskListSaveManager; private TaskListNotificationManager taskListNotificationManager; private TaskListBackupManager taskListBackupManager; private TaskDataManager taskDataManager; private Set<AbstractTaskEditorFactory> taskEditorFactories = new HashSet<AbstractTaskEditorFactory>(); private Set<IHyperlinkDetector> hyperlinkDetectors = new HashSet<IHyperlinkDetector>(); private TreeSet<AbstractTaskRepositoryLinkProvider> repositoryLinkProviders = new TreeSet<AbstractTaskRepositoryLinkProvider>( new OrderComparator()); private TaskListWriter taskListWriter; private ITaskHighlighter highlighter; private boolean initialized = false; private Map<String, Image> brandingIcons = new HashMap<String, Image>(); private Map<String, ImageDescriptor> overlayIcons = new HashMap<String, ImageDescriptor>(); private Set<AbstractDuplicateDetector> duplicateDetectors = new HashSet<AbstractDuplicateDetector>(); private ISaveParticipant saveParticipant; private static final class OrderComparator implements Comparator<AbstractTaskRepositoryLinkProvider> { public int compare(AbstractTaskRepositoryLinkProvider p1, AbstractTaskRepositoryLinkProvider p2) { return p1.getOrder() - p2.getOrder(); } } public enum TaskListSaveMode { ONE_HOUR, THREE_HOURS, DAY; @Override public String toString() { switch (this) { case ONE_HOUR: return "1 hour"; case THREE_HOURS: return "3 hours"; case DAY: return "1 day"; default: return "3 hours"; } } public static TaskListSaveMode fromString(String string) { if (string == null) return null; if (string.equals("1 hour")) return ONE_HOUR; if (string.equals("3 hours")) return THREE_HOURS; if (string.equals("1 day")) return DAY; return null; } public static long fromStringToLong(String string) { long hour = 3600 * 1000; switch (fromString(string)) { case ONE_HOUR: return hour; case THREE_HOURS: return hour * 3; case DAY: return hour * 24; default: return hour * 3; } } } public enum ReportOpenMode { EDITOR, INTERNAL_BROWSER, EXTERNAL_BROWSER; } private static ITaskActivityListener CONTEXT_TASK_ACTIVITY_LISTENER = new ITaskActivityListener() { public void taskActivated(final AbstractTask task) { ContextCorePlugin.getContextManager().activateContext(task.getHandleIdentifier()); } public void taskDeactivated(final AbstractTask task) { ContextCorePlugin.getContextManager().deactivateContext(task.getHandleIdentifier()); } public void activityChanged(ScheduledTaskContainer week) { // ignore } public void taskListRead() { // ignore } }; private static ITaskListNotificationProvider REMINDER_NOTIFICATION_PROVIDER = new ITaskListNotificationProvider() { public Set<ITaskListNotification> getNotifications() { Date currentDate = new Date(); Collection<AbstractTask> allTasks = TasksUiPlugin.getTaskListManager().getTaskList().getAllTasks(); Set<ITaskListNotification> reminders = new HashSet<ITaskListNotification>(); for (AbstractTask task : allTasks) { if (!task.isCompleted() && task.getScheduledForDate() != null && !task.isReminded() && task.getScheduledForDate().compareTo(currentDate) < 0) { reminders.add(new TaskListNotificationReminder(task)); task.setReminded(true); } } return reminders; } }; private static ITaskListNotificationProvider INCOMING_NOTIFICATION_PROVIDER = new ITaskListNotificationProvider() { public Set<ITaskListNotification> getNotifications() { Set<ITaskListNotification> notifications = new HashSet<ITaskListNotification>(); // Incoming Changes for (TaskRepository repository : getRepositoryManager().getAllRepositories()) { AbstractRepositoryConnector connector = getRepositoryManager().getRepositoryConnector( repository.getConnectorKind()); AbstractRepositoryConnectorUi connectorUi = getConnectorUi(repository.getConnectorKind()); if (connectorUi != null && !connectorUi.isCustomNotificationHandling()) { for (AbstractTask repositoryTask : TasksUiPlugin.getTaskListManager() .getTaskList() .getRepositoryTasks(repository.getUrl())) { if ((repositoryTask.getLastReadTimeStamp() == null || repositoryTask.getSynchronizationState() == RepositoryTaskSyncState.INCOMING) && repositoryTask.isNotified() == false) { TaskListNotificationIncoming notification = INSTANCE.getIncommingNotification(connector, repositoryTask); notifications.add(notification); repositoryTask.setNotified(true); } } } } // New query hits for (AbstractRepositoryQuery query : TasksUiPlugin.getTaskListManager().getTaskList().getQueries()) { AbstractRepositoryConnectorUi connectorUi = getConnectorUi(query.getRepositoryKind()); if (!connectorUi.isCustomNotificationHandling()) { for (AbstractTask hit : query.getChildren()) { if (hit.isNotified() == false) { notifications.add(new TaskListNotificationQueryIncoming(hit)); hit.setNotified(true); } } } } return notifications; } }; private final IPropertyChangeListener PREFERENCE_LISTENER = new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(TasksUiPreferenceConstants.ACTIVATE_MULTIPLE)) { TaskListView.getFromActivePerspective().togglePreviousAction( !getPreferenceStore().getBoolean(TasksUiPreferenceConstants.ACTIVATE_MULTIPLE)); getTaskListManager().getTaskActivationHistory().clear(); } // TODO: do we ever get here? if (event.getProperty().equals(ContextPreferenceContstants.PREF_DATA_DIR)) { if (event.getOldValue() instanceof String) { reloadDataDirectory(true); } } } }; private final org.eclipse.jface.util.IPropertyChangeListener PROPERTY_LISTENER = new org.eclipse.jface.util.IPropertyChangeListener() { public void propertyChange(org.eclipse.jface.util.PropertyChangeEvent event) { if (event.getProperty().equals(ContextPreferenceContstants.PREF_DATA_DIR)) { if (event.getOldValue() instanceof String) { reloadDataDirectory(true); } } } }; public TasksUiPlugin() { super(); INSTANCE = this; } @Override public void start(BundleContext context) throws Exception { super.start(context); // NOTE: startup order is very sensitive try { StatusHandler.addStatusHandler(new RepositoryAwareStatusHandler()); WebClientUtil.initCommonsLoggingSettings(); initializeDefaultPreferences(getPreferenceStore()); taskListWriter = new TaskListWriter(); File dataDir = new File(getDataDirectory()); dataDir.mkdirs(); String path = getDataDirectory() + File.separator + ITasksUiConstants.DEFAULT_TASK_LIST_FILE; File taskListFile = new File(path); taskListManager = new TaskListManager(taskListWriter, taskListFile); taskRepositoryManager = new TaskRepositoryManager(taskListManager.getTaskList()); synchronizationManager = new RepositorySynchronizationManager(); // NOTE: initializing extensions in start(..) has caused race // conditions previously TasksUiExtensionReader.initStartupExtensions(taskListWriter); taskRepositoryManager.readRepositories(getRepositoriesFilePath()); // instantiates taskDataManager startOfflineStorageManager(); loadTemplateRepositories(); // NOTE: task list must be read before Task List view can be // initialized taskListManager.init(); taskListManager.addActivityListener(CONTEXT_TASK_ACTIVITY_LISTENER); taskListManager.readExistingOrCreateNewList(); initialized = true; saveParticipant = new ISaveParticipant() { public void doneSaving(ISaveContext context) { } public void prepareToSave(ISaveContext context) throws CoreException { } public void rollback(ISaveContext context) { } public void saving(ISaveContext context) throws CoreException { if (context.getKind() == ISaveContext.FULL_SAVE) { taskListManager.saveTaskList(); taskDataManager.stop(); } } }; ResourcesPlugin.getWorkspace().addSaveParticipant(this, saveParticipant); PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { // NOTE: failure in one part of the initialization should // not prevent others try { // Needs to run after workbench is loaded because it // relies on images. TasksUiExtensionReader.initWorkbenchUiExtensions(); // Needs to happen asynchronously to avoid bug 159706 if (taskListManager.getTaskList().getActiveTask() != null) { taskListManager.activateTask(taskListManager.getTaskList().getActiveTask()); } taskListManager.initActivityHistory(); } catch (Throwable t) { StatusHandler.fail(t, "Could not initialize task activity", false); } try { taskListNotificationManager = new TaskListNotificationManager(); taskListNotificationManager.addNotificationProvider(REMINDER_NOTIFICATION_PROVIDER); taskListNotificationManager.addNotificationProvider(INCOMING_NOTIFICATION_PROVIDER); taskListNotificationManager.startNotification(NOTIFICATION_DELAY); getPreferenceStore().addPropertyChangeListener(taskListNotificationManager); } catch (Throwable t) { StatusHandler.fail(t, "Could not initialize notifications", false); } try { taskListBackupManager = new TaskListBackupManager(); getPreferenceStore().addPropertyChangeListener(taskListBackupManager); synchronizationScheduler = new TaskListSynchronizationScheduler(true); synchronizationScheduler.startSynchJob(); } catch (Throwable t) { StatusHandler.fail(t, "Could not initialize task list backup and synchronization", false); } try { taskListSaveManager = new TaskListSaveManager(); taskListManager.setTaskListSaveManager(taskListSaveManager); ContextCorePlugin.getDefault().getPluginPreferences().addPropertyChangeListener( PREFERENCE_LISTENER); getPreferenceStore().addPropertyChangeListener(PROPERTY_LISTENER); getPreferenceStore().addPropertyChangeListener(synchronizationScheduler); getPreferenceStore().addPropertyChangeListener(taskListManager); // TODO: get rid of this, hack to make decorators show // up on startup TaskRepositoriesView repositoriesView = TaskRepositoriesView.getFromActivePerspective(); if (repositoriesView != null) { repositoriesView.getViewer().refresh(); } checkForCredentials(); } catch (Throwable t) { StatusHandler.fail(t, "Could not finish Tasks UI initialization", false); } } }); } catch (Exception e) { e.printStackTrace(); StatusHandler.fail(e, "Mylyn Task List initialization failed", false); } } private void loadTemplateRepositories() { // Add standard local task repository if (taskRepositoryManager.getRepository(LocalRepositoryConnector.REPOSITORY_URL) == null) { TaskRepository localRepository = new TaskRepository(LocalRepositoryConnector.REPOSITORY_KIND, LocalRepositoryConnector.REPOSITORY_URL, LocalRepositoryConnector.REPOSITORY_VERSION); localRepository.setRepositoryLabel(LocalRepositoryConnector.REPOSITORY_LABEL); localRepository.setAnonymous(true); taskRepositoryManager.addRepository(localRepository, getRepositoriesFilePath()); } // Add the automatically created templates for (AbstractRepositoryConnector connector : taskRepositoryManager.getRepositoryConnectors()) { connector.setTaskDataManager(taskDataManager); for (RepositoryTemplate template : connector.getTemplates()) { if (template.addAutomatically) { try { TaskRepository taskRepository = taskRepositoryManager.getRepository( connector.getConnectorKind(), template.repositoryUrl); if (taskRepository == null) { taskRepository = new TaskRepository(connector.getConnectorKind(), template.repositoryUrl, template.version); taskRepository.setRepositoryLabel(template.label); taskRepository.setAnonymous(true); taskRepositoryManager.addRepository(taskRepository, getRepositoriesFilePath()); } } catch (Throwable t) { StatusHandler.fail(t, "Could not load repository template", false); } } } } } private void checkForCredentials() { for (TaskRepository repository : taskRepositoryManager.getAllRepositories()) { AbstractRepositoryConnector connector = getRepositoryManager().getRepositoryConnector( repository.getConnectorKind()); boolean userManaged = true; if (connector != null) { userManaged = connector.isUserManaged(); } if (!repository.isAnonymous() && !userManaged && (repository.getUserName() == null || repository.getPassword() == null || "".equals(repository.getUserName()) || "".equals(repository.getPassword()))) { try { EditRepositoryWizard wizard = new EditRepositoryWizard(repository); Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); if (shell != null && !shell.isDisposed()) { WizardDialog dialog = new WizardDialog(shell, wizard); dialog.create(); // dialog.setTitle("Repository Credentials Missing"); dialog.setErrorMessage("Authentication credentials missing."); dialog.setBlockOnOpen(true); if (dialog.open() == Dialog.CANCEL) { dialog.close(); return; } } } catch (Exception e) { StatusHandler.fail(e, e.getMessage(), true); } } } } public void earlyStartup() { // ignore } @Override public void stop(BundleContext context) throws Exception { try { if (ResourcesPlugin.getWorkspace() != null) { ResourcesPlugin.getWorkspace().removeSaveParticipant(this); } if (PlatformUI.isWorkbenchRunning()) { getPreferenceStore().removePropertyChangeListener(taskListNotificationManager); getPreferenceStore().removePropertyChangeListener(taskListBackupManager); getPreferenceStore().removePropertyChangeListener(taskListManager); getPreferenceStore().removePropertyChangeListener(synchronizationScheduler); getPreferenceStore().removePropertyChangeListener(PROPERTY_LISTENER); taskListManager.getTaskList().removeChangeListener(taskListSaveManager); taskListManager.dispose(); TaskListColorsAndFonts.dispose(); if (ContextCorePlugin.getDefault() != null) { ContextCorePlugin.getDefault().getPluginPreferences().removePropertyChangeListener( PREFERENCE_LISTENER); } INSTANCE = null; } } catch (Exception e) { StatusHandler.log(e, "Mylyn Task List stop terminated abnormally"); } finally { super.stop(context); } } public String getDefaultDataDirectory() { return ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/' + DIRECTORY_METADATA + '/' + NAME_DATA_DIR; } /** * Only attempt once per startup. */ private boolean attemptMigration = true; public synchronized String getDataDirectory() { if (attemptMigration) { migrateFromLegacyDirectory(); attemptMigration = false; } // return ContextCorePlugin.getDefault().getContextStore().getRootDirectory().getAbsolutePath(); return getPreferenceStore().getString(ContextPreferenceContstants.PREF_DATA_DIR); } private void migrateFromLegacyDirectory() { // Migrate .mylar data folder to .metadata/.mylyn String oldDefaultDataPath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/' + ".mylar"; File oldDefaultDataDir = new File(oldDefaultDataPath); if (oldDefaultDataDir.exists()) { // && !newDefaultDataDir.exists()) { File metadata = new File(ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/' + DIRECTORY_METADATA); if (!metadata.exists()) { if (!metadata.mkdirs()) { StatusHandler.log("Unable to create metadata folder: " + metadata.getAbsolutePath(), this); } } File newDefaultDataDir = new File(getPreferenceStore().getString(ContextPreferenceContstants.PREF_DATA_DIR)); if (metadata.exists()) { if (!oldDefaultDataDir.renameTo(newDefaultDataDir)) { StatusHandler.log("Could not migrate legacy data from " + oldDefaultDataDir.getAbsolutePath() + " to " + TasksUiPlugin.getDefault().getDefaultDataDirectory(), this); } else { StatusHandler.log("Migrated legacy task data from " + oldDefaultDataDir.getAbsolutePath() + " to " + TasksUiPlugin.getDefault().getDefaultDataDirectory(), this); } } } } public void setDataDirectory(String newPath) { getTaskListManager().saveTaskList(); ContextCorePlugin.getContextManager().saveActivityContext(); getPreferenceStore().setValue(ContextPreferenceContstants.PREF_DATA_DIR, newPath); ContextCorePlugin.getDefault().getContextStore().contextStoreMoved(); } /** * Only support task data versions post 0.7 * * @param withProgress */ public void reloadDataDirectory(boolean withProgress) { getTaskListManager().resetTaskList(); getTaskListManager().getTaskActivationHistory().clear(); getRepositoryManager().readRepositories(getRepositoriesFilePath()); loadTemplateRepositories(); ContextCorePlugin.getContextManager().loadActivityMetaContext(); getTaskListManager().setTaskListFile( new File(getDataDirectory() + File.separator + ITasksUiConstants.DEFAULT_TASK_LIST_FILE)); getTaskListManager().readExistingOrCreateNewList(); getTaskListManager().initActivityHistory(); checkForCredentials(); } @Override protected void initializeDefaultPreferences(IPreferenceStore store) { store.setDefault(ContextPreferenceContstants.PREF_DATA_DIR, getDefaultDataDirectory()); store.setDefault(TasksUiPreferenceConstants.FILTER_SUBTASKS, true); store.setDefault(TasksUiPreferenceConstants.NOTIFICATIONS_ENABLED, true); store.setDefault(TasksUiPreferenceConstants.FILTER_PRIORITY, PriorityLevel.P5.toString()); store.setDefault(TasksUiPreferenceConstants.EDITOR_TASKS_RICH, true); store.setDefault(TasksUiPreferenceConstants.ACTIVATE_WHEN_OPENED, false); store.setDefault(TasksUiPreferenceConstants.SHOW_TRIM, false); store.setDefault(TasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_ENABLED, true); store.setDefault(TasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_MILISECONDS, "" + (20 * 60 * 1000)); store.setDefault(TasksUiPreferenceConstants.BACKUP_SCHEDULE, 1); store.setDefault(TasksUiPreferenceConstants.BACKUP_MAXFILES, 20); store.setDefault(TasksUiPreferenceConstants.BACKUP_LAST, 0f); store.setDefault(TasksUiPreferenceConstants.FILTER_ARCHIVE_MODE, true); store.setDefault(TasksUiPreferenceConstants.ACTIVATE_MULTIPLE, false); store.setValue(TasksUiPreferenceConstants.ACTIVATE_MULTIPLE, false); store.setDefault(TasksUiPreferenceConstants.PLANNING_STARTHOUR, 9); store.setDefault(TasksUiPreferenceConstants.PLANNING_ENDHOUR, 18); } public static TaskListManager getTaskListManager() { return taskListManager; } public static TaskListNotificationManager getTaskListNotificationManager() { return INSTANCE.taskListNotificationManager; } /** * Returns the shared instance. */ public static TasksUiPlugin getDefault() { return INSTANCE; } private Map<String, List<IDynamicSubMenuContributor>> menuContributors = new HashMap<String, List<IDynamicSubMenuContributor>>(); public Map<String, List<IDynamicSubMenuContributor>> getDynamicMenuMap() { return menuContributors; } public void addDynamicPopupContributor(String menuPath, IDynamicSubMenuContributor contributor) { List<IDynamicSubMenuContributor> contributors = menuContributors.get(menuPath); if (contributors == null) { contributors = new ArrayList<IDynamicSubMenuContributor>(); menuContributors.put(menuPath, contributors); } contributors.add(contributor); } public String[] getSaveOptions() { String[] options = { TaskListSaveMode.ONE_HOUR.toString(), TaskListSaveMode.THREE_HOURS.toString(), TaskListSaveMode.DAY.toString() }; return options; } public String getBackupFolderPath() { return getDataDirectory() + DEFAULT_PATH_SEPARATOR + ITasksUiConstants.DEFAULT_BACKUP_FOLDER_NAME; } public ITaskHighlighter getHighlighter() { return highlighter; } public void setHighlighter(ITaskHighlighter highlighter) { this.highlighter = highlighter; } public Set<AbstractTaskEditorFactory> getTaskEditorFactories() { return taskEditorFactories; } public void addContextEditor(AbstractTaskEditorFactory contextEditor) { if (contextEditor != null) this.taskEditorFactories.add(contextEditor); } public static TaskRepositoryManager getRepositoryManager() { return taskRepositoryManager; } public void addBrandingIcon(String repositoryType, Image icon) { brandingIcons.put(repositoryType, icon); } public Image getBrandingIcon(String repositoryType) { return brandingIcons.get(repositoryType); } public void addOverlayIcon(String repositoryType, ImageDescriptor icon) { overlayIcons.put(repositoryType, icon); } public ImageDescriptor getOverlayIcon(String repositoryType) { return overlayIcons.get(repositoryType); } public boolean isInitialized() { return initialized; } public IHyperlinkDetector[] getTaskHyperlinkDetectors() { return hyperlinkDetectors.toArray(new IHyperlinkDetector[1]); } public void addTaskHyperlinkDetector(IHyperlinkDetector listener) { if (listener != null) this.hyperlinkDetectors.add(listener); } public void addRepositoryLinkProvider(AbstractTaskRepositoryLinkProvider repositoryLinkProvider) { if (repositoryLinkProvider != null) this.repositoryLinkProviders.add(repositoryLinkProvider); } public TaskListBackupManager getBackupManager() { return taskListBackupManager; } private void startOfflineStorageManager() { //IPath offlineReportsPath = Platform.getStateLocation(TasksUiPlugin.getDefault().getBundle()); File root = new File(this.getDataDirectory() + '/' + FOLDER_OFFLINE); OfflineFileStorage storage = new OfflineFileStorage(root); OfflineCachingStorage cachedStorage = new OfflineCachingStorage(storage); taskDataManager = new TaskDataManager(taskRepositoryManager, cachedStorage); taskDataManager.start(); } public static TaskDataManager getTaskDataManager() { if (INSTANCE == null || INSTANCE.taskDataManager == null) { StatusHandler.fail(null, "Offline reports file not created, try restarting.", true); return null; } else { return INSTANCE.taskDataManager; } } public void addRepositoryConnectorUi(AbstractRepositoryConnectorUi repositoryConnectorUi) { if (!repositoryConnectorUiMap.values().contains(repositoryConnectorUi)) { repositoryConnectorUiMap.put(repositoryConnectorUi.getConnectorKind(), repositoryConnectorUi); } } public static AbstractRepositoryConnectorUi getConnectorUi(String kind) { return repositoryConnectorUiMap.get(kind); } public static TaskListSynchronizationScheduler getSynchronizationScheduler() { return synchronizationScheduler; } public static RepositorySynchronizationManager getSynchronizationManager() { return synchronizationManager; } public void addDuplicateDetector(AbstractDuplicateDetector duplicateDetector) { if (duplicateDetector != null) { duplicateDetectors.add(duplicateDetector); } } public Set<AbstractDuplicateDetector> getDuplicateSearchCollectorsList() { return duplicateDetectors; } public String getRepositoriesFilePath() { return getDataDirectory() + File.separator + TaskRepositoryManager.DEFAULT_REPOSITORIES_FILE; } public boolean canSetRepositoryForResource(IResource resource) { if (resource == null) { return false; } // find first provider that can link repository for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { TaskRepository repository = linkProvider.getTaskRepository(resource, getRepositoryManager()); if (repository != null) { return linkProvider.canSetTaskRepository(resource); } } // find first provider that can set new repository for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { if (linkProvider.canSetTaskRepository(resource)) { return true; } } return false; } /** * Associate a Task Repository with a workbench project * * @param resource * project or resource belonging to a project * @param repository * task repository to associate with given project * @throws CoreException */ public void setRepositoryForResource(IResource resource, TaskRepository repository) throws CoreException { if (resource == null || repository == null) { return; } for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { TaskRepository r = linkProvider.getTaskRepository(resource, getRepositoryManager()); boolean canSetRepository = linkProvider.canSetTaskRepository(resource); if (r != null && !canSetRepository) { return; } if (canSetRepository) { linkProvider.setTaskRepository(resource, repository); return; } } } /** * Retrieve the task repository that has been associated with the given project (or resource belonging to a project) */ public TaskRepository getRepositoryForResource(IResource resource, boolean silent) { if (resource == null) { return null; } for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { TaskRepository repository = linkProvider.getTaskRepository(resource, getRepositoryManager()); if (repository != null) { return repository; } } if (!silent) { MessageDialog.openInformation(null, "No Repository Found", "No repository was found. Associate a Task Repository with this project via the project's property page."); } return null; } /** * Public for testing. */ public static TaskListSaveManager getTaskListSaveManager() { return INSTANCE.taskListSaveManager; } public String getNextNewRepositoryTaskId() { return getTaskDataManager().getNewRepositoryTaskId(); } /** * TODO: move, uses internal class. */ public TaskListNotificationIncoming getIncommingNotification(AbstractRepositoryConnector connector, AbstractTask task) { TaskListNotificationIncoming notification = new TaskListNotificationIncoming(task); RepositoryTaskData newTaskData = getTaskDataManager().getNewTaskData(task.getRepositoryUrl(), task.getTaskId()); RepositoryTaskData oldTaskData = getTaskDataManager().getOldTaskData(task.getRepositoryUrl(), task.getTaskId()); try { if (task.getSynchronizationState().equals(RepositoryTaskSyncState.INCOMING) && task.getLastReadTimeStamp() == null) { notification.setDescription("New unread task"); } else if (newTaskData != null && oldTaskData != null) { notification.setDescription(getChangedDescription(newTaskData, oldTaskData)); notification.setDetails(getChangedAttributes(newTaskData, oldTaskData)); if (connector != null) { AbstractTaskDataHandler offlineHandler = connector.getTaskDataHandler(); if (offlineHandler != null && newTaskData.getLastModified() != null) { Date modified = newTaskData.getAttributeFactory().getDateForAttributeType( RepositoryTaskAttribute.DATE_MODIFIED, newTaskData.getLastModified()); notification.setDate(modified); } } } else { notification.setDescription("Unread task"); } } catch (Throwable t) { StatusHandler.fail(t, "Could not format notification for: " + task, false); } return notification; } private static String getChangedDescription(RepositoryTaskData newTaskData, RepositoryTaskData oldTaskData) { String descriptionText = ""; if (newTaskData.getComments().size() > oldTaskData.getComments().size()) { List<TaskComment> taskComments = newTaskData.getComments(); if (taskComments != null && taskComments.size() > 0) { TaskComment lastComment = taskComments.get(taskComments.size() - 1); if (lastComment != null) { descriptionText += "Comment by " + lastComment.getAuthor() + ":\n "; descriptionText += cleanValue(lastComment.getText()); } } } return descriptionText; } private static String getChangedAttributes(RepositoryTaskData newTaskData, RepositoryTaskData oldTaskData) { List<Change> changes = new ArrayList<Change>(); for (RepositoryTaskAttribute newAttribute : newTaskData.getAttributes()) { // HACK delta_ts is not a standard attribute if ("delta_ts,longdesclength,".contains(newAttribute.getId())) { continue; } List<String> newValues = newAttribute.getValues(); RepositoryTaskAttribute oldAttribute = oldTaskData.getAttribute(newAttribute.getId()); if (oldAttribute == null) { changes.add(getDiff(newAttribute.getName(), null, newValues)); } if (oldAttribute != null) { List<String> oldValues = oldAttribute.getValues(); if (!oldValues.equals(newValues)) { changes.add(getDiff(newAttribute.getName(), oldValues, newValues)); } } } for (RepositoryTaskAttribute oldAttribute : oldTaskData.getAttributes()) { if (oldAttribute.isHidden()) { // may not be a good idea continue; } RepositoryTaskAttribute attribute = newTaskData.getAttribute(oldAttribute.getId()); List<String> values = oldAttribute.getValues(); if (attribute == null && values != null && !values.isEmpty()) { changes.add(getDiff(oldAttribute.getName(), values, null)); } } if (changes.isEmpty()) { return ""; } String details = ""; String sep = ""; int n = 0; for (Change change : changes) { String removed = cleanValues(change.removed); String added = cleanValues(change.added); details += sep + " " + change.field + " " + removed; if (removed.length() > 30) { details += "\n "; } details += " -> " + added; sep = "\n"; // if (!change.removed.isEmpty()) { // details += "- " + change.field + " " + change.removed; // sep = "\n"; // if (!change.added.isEmpty()) { // details += sep; // details += "+ " + change.field + " " + change.added; // sep = "\n"; n++; if (n > 5) { details += "\nOpen to view more changes"; break; } } if (!details.equals("")) { return "Attributes Changed:\n" + details; } return details; } private static String cleanValues(List<String> values) { StringBuilder sb = new StringBuilder(); sb.append("["); boolean first = true; for (String value : values) { if (!first) sb.append(", "); sb.append(cleanValue(value)); } sb.append("]"); return sb.toString(); } private static String cleanValue(String value) { String commentText = value.replaceAll("\\s", " ").trim(); if (commentText.length() > 60) { commentText = commentText.substring(0, 55) + "..."; } return commentText; } private static Change getDiff(String field, List<String> oldValues, List<String> newValues) { Change change = new Change(field, newValues); if (oldValues != null) { for (String value : oldValues) { if (change.added.contains(value)) { change.added.remove(value); } else { change.removed.add(value); } } } return change; } private static class Change { final String field; final List<String> added; final List<String> removed = new ArrayList<String>(); public Change(String field, List<String> newValues) { this.field = field; this.added = new ArrayList<String>(newValues); } } }
package org.mwc.debrief.core; import org.eclipse.ui.IFolderLayout; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPerspectiveFactory; import org.eclipse.ui.IPlaceholderFolderLayout; import org.mwc.cmap.core.CorePlugin; /** * @author ian.mayo * */ public class DebriefPerspectiveFactory implements IPerspectiveFactory { /** * @param layout */ @SuppressWarnings("deprecation") public void createInitialLayout(final IPageLayout layout) { // Get the editor area. final String editorArea = layout.getEditorArea(); // Top left: Resource Navigator view and Bookmarks view placeholder final IFolderLayout topLeft = layout.createFolder("topLeft", IPageLayout.LEFT, 0.25f, editorArea); topLeft.addView(IPageLayout.ID_RES_NAV); topLeft.addView(CorePlugin.TIME_CONTROLLER); topLeft.addPlaceholder(CorePlugin.TIME_BAR); // split the time one - so we can insert the track tote // Top left: Resource Navigator view and Bookmarks view placeholder final IFolderLayout midLeft = layout.createFolder("midLeft", IPageLayout.BOTTOM, 0.3f, "topLeft"); midLeft.addView(IPageLayout.ID_PROP_SHEET); midLeft.addView(CorePlugin.TOTE); midLeft.addView(CorePlugin.OVERVIEW_PLOT); midLeft.addPlaceholder(CorePlugin.DIS_LISTENER_VIEW); midLeft.addPlaceholder(CorePlugin.POLYGON_EDITOR); // Bottom left: Outline view and Property Sheet view final IFolderLayout bottomLeft = layout.createFolder("bottomLeft", IPageLayout.BOTTOM, 0.40f, "midLeft"); bottomLeft.addView(IPageLayout.ID_OUTLINE); bottomLeft.addPlaceholder(DebriefPlugin.MULTI_PATH); // bottom: placeholder for the xyplot final IPlaceholderFolderLayout bottomPanel = layout.createPlaceholderFolder("bottom", IPageLayout.BOTTOM, 0.7f, editorArea); bottomPanel.addPlaceholder(CorePlugin.XY_PLOT + ":*"); bottomPanel.addPlaceholder(IPageLayout.ID_BOOKMARKS); bottomPanel.addPlaceholder(IPageLayout.ID_TASK_LIST); bottomPanel.addPlaceholder(CorePlugin.NARRATIVE_VIEWER); // RIGHT: SATC contributions final IPlaceholderFolderLayout right = layout.createPlaceholderFolder("right", IPageLayout.RIGHT, 0.6f, editorArea); right.addPlaceholder(DebriefPlugin.SATC_MAINTAIN_CONTRIBUTIONS); right.addPlaceholder(CorePlugin.GRID_EDITOR); right.addPlaceholder(CorePlugin.STACKED_DOTS); right.addPlaceholder(CorePlugin.FREQ_RESIDUALS); // and our view shortcuts layout.addShowViewShortcut(IPageLayout.ID_OUTLINE); layout.addShowViewShortcut(CorePlugin.NARRATIVE_VIEWER); layout.addShowViewShortcut("org.mwc.cmap.narrative.views.NarrativeViewer2"); layout.addShowViewShortcut(CorePlugin.TIME_CONTROLLER); layout.addShowViewShortcut(CorePlugin.TIME_BAR); layout.addShowViewShortcut(CorePlugin.TOTE); layout.addShowViewShortcut(CorePlugin.STACKED_DOTS); layout.addShowViewShortcut(CorePlugin.FREQ_RESIDUALS); layout.addShowViewShortcut(CorePlugin.GRID_EDITOR); layout.addShowViewShortcut(CorePlugin.OVERVIEW_PLOT); layout.addShowViewShortcut(CorePlugin.DIS_LISTENER_VIEW); layout.addShowViewShortcut(DebriefPlugin.SENSOR_FUSION); layout.addShowViewShortcut(DebriefPlugin.MULTI_PATH); layout.addShowViewShortcut(DebriefPlugin.TIME_BAR); layout.addShowViewShortcut(DebriefPlugin.SATC_MAINTAIN_CONTRIBUTIONS); // it via action (so we can populate it) layout.addShowViewShortcut(IPageLayout.ID_RES_NAV); layout.addShowViewShortcut(IPageLayout.ID_PROP_SHEET); layout.addShowViewShortcut(IPageLayout.ID_BOOKMARKS); // and the error log layout.addShowViewShortcut("org.eclipse.pde.runtime.LogView"); // hey - try to add the 'new plot' to the New menu layout.addNewWizardShortcut("org.mwc.debrief.core.wizards.NewProjectWizard"); layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.folder"); layout.addNewWizardShortcut("org.mwc.debrief.core.wizards.NewPlotWizard"); // ok - make sure the debrief action sets are visible // The actionSets ext point has been moved to commands/menus // layout.addActionSet("org.mwc.debrief.core"); } }
package org.osgi.test.support.compatibility; /** * A classic Semaphore class. */ public class Semaphore { int count = 0; /** * Creates a new Semaphore with 0 as a start value. */ public Semaphore() { this(0); } public Semaphore(int startValue) throws IllegalArgumentException { if(startValue < 0) { throw new IllegalArgumentException("startValue can't be lower than 0"); } synchronized (this) { count = startValue; } } /** * Waits until a signal is (or has been) given. */ public void waitForSignal() throws InterruptedException { waitForSignal(0); } /** * Waits until a signal is (or has been) given. * * @param timeout The maximum number of milliseconds to wait for a signal or * 0 to wait indefinitely. * @return true if the signal is received; false if the wait times out. */ public synchronized boolean waitForSignal(long timeout) throws InterruptedException { while (count == 0) { wait(timeout); if ((count == 0) && (timeout != 0)) { return false; } } count return true; } /** * Give the signal. */ public synchronized void signal() { count++; notify(); } }
package com.IanThomas.resume; import rajawali.RajawaliActivity; import android.annotation.SuppressLint; import android.opengl.GLSurfaceView; import android.os.Build; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.widget.FrameLayout; import com.IanThomas.resume.adapters.ResumeFragmentPagerAdapter; import com.IanThomas.resume.gles.CubeRenderer; import com.IanThomas.resume.transformers.CubeTransformer; import com.IanThomas.resume.views.NavigatorView; public class MainActivity extends RajawaliActivity { public MainActivity() { deferGLSurfaceViewCreation(true); } @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); // Init the 3D engine for the background mLayout = (FrameLayout) LayoutInflater.from(this).inflate( R.layout.activity_main, null, false); setContentView(mLayout); mSurfaceView = (GLSurfaceView) findViewById(R.id.surface_view); mSurfaceView.setEGLContextClientVersion(2); // Init the 3D renderer final CubeRenderer renderer = new CubeRenderer(this); renderer.setSurfaceView(mSurfaceView); setRenderer(renderer); final ResumeFragmentPagerAdapter mSectionsPagerAdapter = new ResumeFragmentPagerAdapter( getFragmentManager()); final ViewPager mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setPageTransformer(true, new CubeTransformer()); final NavigatorView navView = (NavigatorView) findViewById(R.id.navigator); navView.setFragments(mSectionsPagerAdapter.getFragments()); mViewPager.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int position) { } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { navView.onPageScrolled(position, positionOffset); } @Override public void onPageScrollStateChanged(int state) { /* * TODO If the GPU is "meh" pause background rendering while the * foreground updates. Looking at you Galaxy Nexus. */ // if (state == 0) { // mSurfaceView.onResume(); // } else { // mSurfaceView.onPause(); } }); } @SuppressLint("InlinedApi") @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } } }
package com.android.mms.data; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import android.content.AsyncQueryHandler; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.Telephony.Threads; import android.provider.Telephony.Sms.Conversations; import android.text.TextUtils; import android.util.Log; import com.android.mms.R; import com.android.mms.transaction.MessagingNotification; import com.android.mms.ui.MessageUtils; import com.android.mms.util.DraftCache; /** * An interface for finding information about conversations and/or creating new ones. */ public class Conversation { private static final String TAG = "Conversation"; private static final Uri sAllThreadsUri = Threads.CONTENT_URI.buildUpon().appendQueryParameter("simple", "true").build(); private static final String[] ALL_THREADS_PROJECTION = { Threads._ID, Threads.DATE, Threads.MESSAGE_COUNT, Threads.RECIPIENT_IDS, Threads.SNIPPET, Threads.SNIPPET_CHARSET, Threads.READ, Threads.ERROR, Threads.HAS_ATTACHMENT }; private static final int ID = 0; private static final int DATE = 1; private static final int MESSAGE_COUNT = 2; private static final int RECIPIENT_IDS = 3; private static final int SNIPPET = 4; private static final int SNIPPET_CS = 5; private static final int READ = 6; private static final int ERROR = 7; private static final int HAS_ATTACHMENT = 8; private final Context mContext; // The thread ID of this conversation. Can be zero in the case of a // new conversation where the recipient set is changing as the user // types and we have not hit the database yet to create a thread. private long mThreadId; private ContactList mRecipients; // The current set of recipients. private long mDate; // The last update time. private int mMessageCount; // Number of messages. private String mSnippet; // Text of the most recent message. private boolean mHasUnreadMessages; // True if there are unread messages. private boolean mHasAttachment; // True if any message has an attachment. private boolean mHasError; // True if any message is in an error state. private Conversation(Context context) { mContext = context; mRecipients = new ContactList(); mThreadId = 0; } private Conversation(Context context, long threadId) { mContext = context; loadFromThreadId(threadId); } private Conversation(Context context, Cursor cursor, boolean allowQuery) { mContext = context; fillFromCursor(context, this, cursor, allowQuery); } /** * Create a new conversation with no recipients. {@link setRecipients} can * be called as many times as you like; the conversation will not be * created in the database until {@link ensureThreadId} is called. */ private static Conversation createNew(Context context) { return new Conversation(context); } /** * Find the conversation matching the provided thread ID. */ public static Conversation get(Context context, long threadId) { synchronized (Cache.getInstance()) { Conversation conv = Cache.get(threadId); if (conv != null) return conv; conv = new Conversation(context, threadId); Cache.put(conv); return conv; } } /** * Find the conversation matching the provided recipient set. * When called with an empty recipient list, equivalent to {@link createEmpty}. */ public static Conversation get(Context context, ContactList recipients) { // If there are no recipients in the list, make a new conversation. if (recipients.size() < 1) { return createNew(context); } synchronized (Cache.getInstance()) { Conversation conv = Cache.get(recipients); if (conv != null) return conv; long threadId = getOrCreateThreadId(context, recipients); conv = new Conversation(context, threadId); Cache.put(conv); return conv; } } /** * Find the conversation matching in the specified Uri. Example * forms: {@value content://mms-sms/conversations/3} or * {@value sms:+12124797990}. * When called with a null Uri, equivalent to {@link createEmpty}. */ public static Conversation get(Context context, Uri uri) { if (uri == null) { return createNew(context); } // Handle a conversation URI if (uri.getPathSegments().size() >= 2) { try { long threadId = Long.parseLong(uri.getPathSegments().get(1)); return get(context, threadId); } catch (NumberFormatException exception) { Log.e(TAG, "Invalid URI: " + uri); } } String recipient = uri.getSchemeSpecificPart(); return get(context, ContactList.getByNumbers(recipient, false)); } /** * Returns a temporary Conversation (not representing one on disk) wrapping * the contents of the provided cursor. The cursor should be the one * returned to your AsyncQueryHandler passed in to {@link startQueryForAll}. * The recipient list of this conversation can be empty if the results * were not in cache. */ public static Conversation from(Context context, Cursor cursor) { return new Conversation(context, cursor, false); } /** * Marks all messages in this conversation as read and updates * relevant notifications. This method returns immediately; * work is dispatched to a background thread. */ public synchronized void markAsRead() { // If this thread has no unread messages, there's nothing to do. if (!hasUnreadMessages()) { return; } // If we have no Uri to mark (as in the case of a conversation that // has not yet made its way to disk), there's nothing to do. final Uri threadUri = getUri(); if (threadUri == null) return; // TODO: make this once as a static? final ContentValues values = new ContentValues(1); values.put("read", 1); new Thread(new Runnable() { public void run() { mContext.getContentResolver().update(threadUri, values, "read=0", null); MessagingNotification.updateAllNotifications(mContext); } }).start(); } /** * Returns a content:// URI referring to this conversation, * or null if it does not exist on disk yet. */ public synchronized Uri getUri() { if (mThreadId <= 0) return null; return ContentUris.withAppendedId(Threads.CONTENT_URI, mThreadId); } /** * Return the Uri for all messages in the given thread ID. * @deprecated */ public static Uri getUri(long threadId) { // TODO: Callers using this should really just have a Conversation // and call getUri() on it, but this guarantees no blocking. return ContentUris.withAppendedId(Threads.CONTENT_URI, threadId); } /** * Returns the thread ID of this conversation. Can be zero if * {@link ensureThreadId} has not been called yet. */ public synchronized long getThreadId() { return mThreadId; } /** * Guarantees that the conversation has been created in the database. * This will make a blocking database call if it hasn't. * * @return The thread ID of this conversation in the database */ public synchronized long ensureThreadId() { if (mThreadId <= 0) { mThreadId = getOrCreateThreadId(mContext, mRecipients); } return mThreadId; } public synchronized void clearThreadId() { mThreadId = 0; } /** * Sets the list of recipients associated with this conversation. * If called, {@link ensureThreadId} must be called before the next * operation that depends on this conversation existing in the * database (e.g. storing a draft message to it). */ public synchronized void setRecipients(ContactList list) { mRecipients = list; // Invalidate thread ID because the recipient set has changed. mThreadId = 0; } /** * Returns the recipient set of this conversation. */ public synchronized ContactList getRecipients() { return mRecipients; } /** * Returns true if a draft message exists in this conversation. */ public synchronized boolean hasDraft() { if (mThreadId <= 0) return false; return DraftCache.getInstance().hasDraft(mThreadId); } /** * Sets whether or not this conversation has a draft message. */ public synchronized void setDraftState(boolean hasDraft) { if (mThreadId <= 0) return; DraftCache.getInstance().setDraftState(mThreadId, hasDraft); } /** * Returns the time of the last update to this conversation in milliseconds, * on the {@link System.currentTimeMillis} timebase. */ public synchronized long getDate() { return mDate; } /** * Returns the number of messages in this conversation, excluding the draft * (if it exists). */ public synchronized int getMessageCount() { return mMessageCount; } /** * Returns a snippet of text from the most recent message in the conversation. */ public synchronized String getSnippet() { return mSnippet; } /** * Returns true if there are any unread messages in the conversation. */ public synchronized boolean hasUnreadMessages() { return mHasUnreadMessages; } /** * Returns true if any messages in the conversation have attachments. */ public synchronized boolean hasAttachment() { return mHasAttachment; } /** * Returns true if any messages in the conversation are in an error state. */ public synchronized boolean hasError() { return mHasError; } private static long getOrCreateThreadId(Context context, ContactList list) { HashSet<String> recipients = new HashSet<String>(); for (Contact c : list) { recipients.add(c.getNumber()); } return Threads.getOrCreateThreadId(context, recipients); } /* * The primary key of a conversation is its recipient set; override * equals() and hashCode() to just pass through to the internal * recipient sets. */ @Override public synchronized boolean equals(Object obj) { try { Conversation other = (Conversation)obj; return (mRecipients.equals(other.mRecipients)); } catch (ClassCastException e) { return false; } } @Override public synchronized int hashCode() { return mRecipients.hashCode(); } @Override public synchronized String toString() { return String.format("[%s] (tid %d)", mRecipients.serialize(), mThreadId); } /** * Remove any obsolete conversations sitting around on disk. * @deprecated */ public static void cleanup(Context context) { // TODO: Get rid of this awful hack. context.getContentResolver().delete(Threads.OBSOLETE_THREADS_URI, null, null); } /** * Start a query for all conversations in the database on the specified * AsyncQueryHandler. * * @param handler An AsyncQueryHandler that will receive onQueryComplete * upon completion of the query * @param token The token that will be passed to onQueryComplete */ public static void startQueryForAll(AsyncQueryHandler handler, int token) { handler.cancelOperation(token); handler.startQuery(token, null, sAllThreadsUri, ALL_THREADS_PROJECTION, null, null, Conversations.DEFAULT_SORT_ORDER); } /** * Start a delete of the conversation with the specified thread ID. * * @param handler An AsyncQueryHandler that will receive onDeleteComplete * upon completion of the conversation being deleted * @param token The token that will be passed to onDeleteComplete * @param threadId Thread ID of the conversation to be deleted */ public static void startDelete(AsyncQueryHandler handler, int token, long threadId) { Uri uri = ContentUris.withAppendedId(Threads.CONTENT_URI, threadId); handler.startDelete(token, null, uri, "locked=0", null); } /** * Start deleting all conversations in the database. * @param handler An AsyncQueryHandler that will receive onDeleteComplete * upon completion of all conversations being deleted * @param token The token that will be passed to onDeleteComplete */ public static void startDeleteAll(AsyncQueryHandler handler, int token) { handler.startDelete(token, null, Threads.CONTENT_URI, "locked=0", null); } /** * Fill the specified conversation with the values from the specified * cursor, possibly setting recipients to empty if {@value allowQuery} * is false and the recipient IDs are not in cache. The cursor should * be one made via {@link startQueryForAll}. */ private static void fillFromCursor(Context context, Conversation conv, Cursor c, boolean allowQuery) { synchronized (conv) { conv.mThreadId = c.getLong(ID); conv.mDate = c.getLong(DATE); conv.mMessageCount = c.getInt(MESSAGE_COUNT); // Replace the snippet with a default value if it's empty. String snippet = MessageUtils.extractEncStrFromCursor(c, SNIPPET, SNIPPET_CS); if (TextUtils.isEmpty(snippet)) { snippet = context.getString(R.string.no_subject_view); } conv.mSnippet = snippet; conv.mHasUnreadMessages = (c.getInt(READ) == 0); conv.mHasError = (c.getInt(ERROR) != 0); conv.mHasAttachment = (c.getInt(HAS_ATTACHMENT) != 0); String recipientIds = c.getString(RECIPIENT_IDS); conv.mRecipients = ContactList.getByIds(recipientIds, allowQuery); } } /** * Private cache for the use of the various forms of Conversation.get. */ private static class Cache { private static Cache sInstance = new Cache(); static Cache getInstance() { return sInstance; } private final HashSet<Conversation> mCache; private Cache() { mCache = new HashSet<Conversation>(10); } /** * Return the conversation with the specified thread ID, or * null if it's not in cache. */ static Conversation get(long threadId) { synchronized (sInstance) { for (Conversation c : sInstance.mCache) { if (c.getThreadId() == threadId) { return c; } } } return null; } /** * Return the conversation with the specified recipient * list, or null if it's not in cache. */ static Conversation get(ContactList list) { synchronized (sInstance) { for (Conversation c : sInstance.mCache) { if (c.getRecipients().equals(list)) { return c; } } } return null; } /** * Put the specified conversation in the cache. The caller * should not place an already-existing conversation in the * cache, but rather update it in place. */ static void put(Conversation c) { synchronized (sInstance) { // We update cache entries in place so people with long- // held references get updated. if (sInstance.mCache.contains(c)) { throw new IllegalStateException("cache already contains " + c + " threadId: " + c.mThreadId); } sInstance.mCache.add(c); } } /** * Remove all conversations from the cache that are not in * the provided set of thread IDs. */ static void keepOnly(Set<Long> threads) { synchronized (sInstance) { Iterator<Conversation> iter = sInstance.mCache.iterator(); while (iter.hasNext()) { Conversation c = iter.next(); if (!threads.contains(c.getThreadId())) { iter.remove(); } } } } } /** * Set up the conversation cache. To be called once at application * startup time. */ public static void init(final Context context) { new Thread(new Runnable() { public void run() { cacheAllThreads(context); } }).start(); } private static void cacheAllThreads(Context context) { synchronized (Cache.getInstance()) { // Keep track of what threads are now on disk so we // can discard anything removed from the cache. HashSet<Long> threadsOnDisk = new HashSet<Long>(); // Query for all conversations. Cursor c = context.getContentResolver().query(sAllThreadsUri, ALL_THREADS_PROJECTION, null, null, null); try { while (c.moveToNext()) { long threadId = c.getLong(ID); threadsOnDisk.add(threadId); // Try to find this thread ID in the cache. Conversation conv = Cache.get(threadId); if (conv == null) { // Make a new Conversation and put it in // the cache if necessary. conv = new Conversation(context, c, true); Cache.put(conv); } else { // Or update in place so people with references // to conversations get updated too. fillFromCursor(context, conv, c, true); } } } finally { c.close(); } // Purge the cache of threads that no longer exist on disk. Cache.keepOnly(threadsOnDisk); } } private void loadFromThreadId(long threadId) { Cursor c = mContext.getContentResolver().query(sAllThreadsUri, ALL_THREADS_PROJECTION, "_id=" + Long.toString(threadId), null, null); try { if (c.moveToFirst()) { fillFromCursor(mContext, this, c, true); } else { throw new IllegalArgumentException("Can't find thread ID " + threadId); } } finally { c.close(); } } }
package chat21.android.demo; import android.app.Application; import android.content.Context; import android.support.multidex.MultiDex; import android.util.Log; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import chat21.android.core.ChatManager; import chat21.android.core.users.models.ChatUser; import chat21.android.core.users.models.IChatUser; import chat21.android.ui.ChatUI; import chat21.android.ui.login.ChatLoginActivity; public class AppContext extends Application { private static final String TAG = AppContext.class.getName(); private static AppContext instance; @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } @Override public void onCreate() { super.onCreate(); instance = this; initChatSDK(); } private void initChatSDK() { // it creates the chat configurations ChatManager.Configuration mChatConfiguration = new ChatManager.Configuration.Builder(getString(R.string.tenant)).firebaseUrl("https://chat-v2-dev.firebaseio.com/").build(); FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser(); // assuming you have a login, check if the logged user (converted to IChatUser) is valid if (FirebaseAuth.getInstance().getCurrentUser() != null) { IChatUser iChatUser = new ChatUser(); iChatUser.setId(currentUser.getUid()); iChatUser.setEmail(currentUser.getEmail()); ChatManager.start(this, mChatConfiguration, iChatUser); Log.i(TAG, "chat has been initialized with success"); ChatUI.getInstance().setContext(instance); Log.i(TAG, "ChatUI has been initialized with success"); } else { Log.w(TAG, "chat can't be initialized because chatUser is null"); } } }
package com.example.idk.myuber; import android.app.ProgressDialog; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URLEncoder; public class Httpget { static String[][] coordinates = new String[100][2]; static String[] bike_nums = new String[100]; static int[] bike_ratings = new int[100]; static String[] owner_array_phone_num = new String[100]; static String[] owner_array_first_name = new String[100]; static String[] owner_array_last_name = new String[100]; static String cc; static String email; static int experience; static int user_rating; static int owner_rating; static String[] bike_owner_nums = new String[100]; static int current_bikes; static String owner_first_name; static String owner_last_name; static String owner_phone_num; static ProgressDialog progressDialog; static JSONArray getJson(HttpEntity httpentity) { InputStream is = null; String received; JSONArray jObj = null; if (httpentity == null) { Log.v("NULL", "ISNULL"); } try { is = httpentity.getContent(); } catch (IllegalStateException e1) { Log.v("LOG", "EXCEPTION7"); e1.printStackTrace(); } catch (IOException e1) { Log.v("LOG", "EXCEPTION8"); e1.printStackTrace(); } try { if (is == null) { Log.d("ERRORR", "IT IS NULL"); } BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); Log.v("LOG", "EXCEPTION10"); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); received = sb.toString(); Log.v("LOG", "EXCEPTION11"); if (received == null) { Log.v("LOG", "EXCEPTION12"); } Log.v("LOG", "received" + received); jObj = new JSONArray(received); Log.v("LOG", String.valueOf(jObj.length())); } catch (Exception e) { Log.v("LOG", "EXCEPTION1N"); e.printStackTrace(); } Log.v("JSON", jObj.toString()); return jObj; } public class bikeTask extends AsyncTask<String, Void, JSONArray> { public bikeTask() { super(); } @Override protected JSONArray doInBackground(String... params) { try { String lat = "36.9999"; String lon = "-122.054"; String URL = "http: HttpGet httpget = new HttpGet(URL); Log.v("URL1V", URL); ResponseHandler<String> responseHandler = new BasicResponseHandler(); HttpResponse SetServerString; Log.v("LOGV", "EXCEPTION3N"); HttpClient Client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(Client.getParams(), 10000); Log.v("LOGV", "EXCEPTION4N"); SetServerString = Client.execute(httpget); ResponseHandler<String> handler = new BasicResponseHandler(); Log.v("LOGV", "EXCEPTION5N"); HttpEntity httpentity = SetServerString.getEntity(); JSONArray result = getJson(httpentity); Log.v("LOGV", "EXCEPTION5N"); Log.v("RESULTV", result.toString()); return result; } catch (Exception e) { Log.v("LOGV", "EXCEPTION2N"); e.printStackTrace(); } return null; } @Override public void onPostExecute(JSONArray jobj) { parseBike(jobj); MapsActivity.makeMarkers(); Log.v("JSON", String.valueOf(jobj.length())); } } public class myTask extends AsyncTask<String, Void, JSONArray> { public myTask() { super(); } @Override protected JSONArray doInBackground(String... params) { try { String URL = "http: HttpGet httpget = new HttpGet(URL); Log.v("URL", params[0]); ResponseHandler<String> responseHandler = new BasicResponseHandler(); HttpResponse SetServerString; Log.v("LOG", "EXCEPTION3N"); HttpClient Client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(Client.getParams(), 10000); Log.v("LOG", "EXCEPTION4N"); SetServerString = Client.execute(httpget); ResponseHandler<String> handler = new BasicResponseHandler(); Log.v("LOG", "EXCEPTION5N"); HttpEntity httpentity = SetServerString.getEntity(); JSONArray result = getJson(httpentity); Log.v("RESULT", result.toString()); return result; } catch (Exception e) { Log.v("LOG", "EXCEPTION2N"); e.printStackTrace(); } return null; } @Override public void onPostExecute(JSONArray jobj) { parseUser(jobj); Log.v("JSONUSER", String.valueOf(jobj.length())); } } public JSONArray newBike(Bike new_bike) { String URL = "http: JSONArray result = null; try { HttpGet httpget = new HttpGet(URL); ResponseHandler<String> responseHandler = new BasicResponseHandler(); HttpResponse SetServerString; HttpClient Client = new DefaultHttpClient(); SetServerString = Client.execute(httpget); HttpEntity httpentity = SetServerString.getEntity(); result = getJson(httpentity); } catch (Exception e) { Log.v("LOG", "EXCEPTIONN"); e.printStackTrace(); } return result; } public static void parseUser(JSONArray jObj) { try { JSONObject temp = jObj.getJSONObject(0); //sweg owner_first_name = temp.getString("first"); owner_last_name = temp.getString("last"); cc = temp.getString("card"); owner_phone_num = temp.getString("phone"); email = temp.getString("phone"); owner_rating = Integer.parseInt(temp.getString("orating")); user_rating = Integer.parseInt(temp.getString("urating")); experience = Integer.parseInt(temp.getString("exp")); Log.v("PARSE", owner_first_name); } catch (Exception e) { Log.v("LOG", "EXCEPTIONN"); e.printStackTrace(); } } public void parseBike(JSONArray jObj) { try { for (int i = 0; i < jObj.length(); i++) { JSONObject temp = jObj.getJSONObject(i); Log.v("PARS", temp.toString()); coordinates[current_bikes][0] = temp.getString("lat"); coordinates[current_bikes][1] = temp.getString("lon"); bike_nums[current_bikes] = temp.getString("bikeid"); bike_ratings[current_bikes] = Integer.parseInt(temp.getString("rating")); bike_owner_nums[current_bikes] = temp.getString("owner"); current_bikes++; } Log.v("PARS", String.valueOf(current_bikes)); } catch (Exception e) { //Log.v("LOG", String.valueOf(jObj.length())); e.printStackTrace(); } } public String getOwner_first_name() { return owner_first_name; } public String getOwner_last_name() { return owner_last_name; } public String getCc() { return cc; } public String getOwner_phone_num() { return owner_phone_num; } public String getEmail() { return email; } public int getOwner_rating() { return owner_rating; } public int getUser_rating() { return user_rating; } public int getExperience() { return experience; } public String getBike_nums(int index) { return bike_nums[index]; } public int getBike_ratings(int index) { return bike_ratings[index]; } public String[][] getCoordinates() { return coordinates; } public String getBike_owner_num(int index) { return bike_owner_nums[index]; } public String getLat(int owner) { for (int i = 0; i < current_bikes; i++) { if (Integer.parseInt(bike_owner_nums[i]) == owner) { return coordinates[i][0]; } } return null; } public String getLon(int owner) { for (int i = 0; i < current_bikes; i++) { if (Integer.parseInt(bike_owner_nums[i]) == owner) { return coordinates[i][1]; } } return null; } public String getOwner(String lat, String lon) { for (int i = 0; i < current_bikes; i++) { if (coordinates[i][0].equals(lat) && coordinates[i][1].equals(lon)) { return bike_owner_nums[i]; } } return null; } public class newBike extends AsyncTask<String, Void, JSONArray> { ProgressDialog pd; public newBike() { super(); } @Override protected void onPreExecute() { super.onPreExecute(); pd = new ProgressDialog(PostBike2.context); pd.setMessage("Loading.."); pd.show(); } @Override protected JSONArray doInBackground(String... params) { try { Log.v("OOO", String.valueOf(params)); String owner = params[0]; String lat = params[1]; String lon = params[2]; String rating = params[3]; JSONObject obj = new JSONObject(); obj.put("owner", owner); obj.put("lat", lat); obj.put("lon", lon); obj.put("rating", rating); String URL = "http://home.loosescre.ws/~keith/astwe/server.php?command=newbike&data=" + Uri.encode(obj.toString()); //String s = URLEncoder.encode(URL); HttpGet httpget = new HttpGet(URL); //Log.v("URL", params[0]); ResponseHandler<String> responseHandler = new BasicResponseHandler(); HttpResponse SetServerString; Log.v("LOG", "EXCEPTION3N"); HttpClient Client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(Client.getParams(), 10000); Log.v("LOG", "EXCEPTION4N"); SetServerString = Client.execute(httpget); ResponseHandler<String> handler = new BasicResponseHandler(); Log.v("LOG", "EXCEPTION5N"); HttpEntity httpentity = SetServerString.getEntity(); //JSONArray result = getJson(httpentity); //Log.v("RESULT", result.toString()); return null; } catch (Exception e) { Log.v("LOGV", "EXCEPTION2N"); e.printStackTrace(); } return null; } @Override protected void onPostExecute(JSONArray jobj) { if(jobj == null) Log.v("JSONUESR", "null"); super.onPostExecute(jobj); if(pd != null) pd.dismiss(); Intent intent = new Intent(PostBike2.context, Main_Activity.class); //MapsActivity.makeMarkers(); PostBike2.context.startActivity(intent); } } }
package com.i906.mpt.qibla; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.graphics.RectF; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Handler; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.Display; import android.view.OrientationEventListener; import android.view.Surface; import android.view.View; import android.view.WindowManager; import com.i906.mpt.R; /** * @author Noorzaini Ilhami */ public class CompassView extends View implements SensorEventListener { private static final float THICKNESS_SCALE = 0.02f; private int mDeviceOrientation = 0; private int mAccentColor; private boolean mUseRotation = false; private boolean mUseAccelerometer = false; private boolean mUseMagnetic = false; private SensorManager mSensorManager; private Sensor mGravitySensor; private Sensor mMagneticSensor; private Sensor mRotationSensor; private float[] mGravity = new float[3]; private float[] mGeomagnetic = new float[3]; private float[] mRotationVector = new float[3]; private float[] mRotation = new float[9]; private float[] mRotationMapped = new float[9]; private float[] mOrientation = new float[3]; private float mAzimuth = 292; private float mDirection; private boolean isUpdateTaskRunning = false; private Handler mHandler = new Handler(); private ElapsedUpdater mUpdater; private Bitmap mArrowBitmap; private Matrix mArrowRotator; private Paint mOuterCirclePaint; private Paint mCirclePaint; private Paint mWhiteArrowPaint; private Paint mArcPaint; private RectF mCircleInnerBounds; private RectF mArcInnerBounds; private RectF mArcCenterBounds; private float smoothSweep; private float smoothDelta; private float mDirectionDelta; private float mLastDirection; private Display mDefaultDisplay; private OrientationEventListener mOrientationEventListener; public CompassView(Context context) { this(context, null); } public CompassView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CompassView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initSensors(); mAccentColor = ContextCompat.getColor(getContext(), R.color.colorAccent); mOrientationEventListener = new OrientationEventListener(getContext()) { @Override public void onOrientationChanged(int i) { configureOrientation(); } }; } private void initPaints(int w, int h) { mOuterCirclePaint = new Paint(); mOuterCirclePaint.setAntiAlias(true); mOuterCirclePaint.setColor(Color.WHITE); mOuterCirclePaint.setStrokeWidth(w * THICKNESS_SCALE); mOuterCirclePaint.setStyle(Paint.Style.STROKE); mWhiteArrowPaint = new Paint(); mWhiteArrowPaint.setAntiAlias(true); mWhiteArrowPaint.setColor(Color.WHITE); mCirclePaint = new Paint(); mCirclePaint.setAntiAlias(true); mCirclePaint.setColor(mAccentColor); float thickness = w * THICKNESS_SCALE * 2; mArcPaint = new Paint(); mArcPaint.setAntiAlias(true); mArcPaint.setColor(mAccentColor); mArcPaint.setStrokeWidth(thickness); mArcPaint.setStyle(Paint.Style.STROKE); } private void updateOuterCirclePaint(float p) { int color = swapColor(mAccentColor, Color.WHITE, p); mOuterCirclePaint.setColor(color); } private void initSensors() { mDefaultDisplay = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay(); mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE); mGravitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mMagneticSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); mRotationSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR); } private void initArrows(int w, int h) { mArrowBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); mArrowBitmap.eraseColor(Color.TRANSPARENT); Canvas arrowCanvas = new Canvas(mArrowBitmap); mArrowRotator = new Matrix(); int hw = w / 2; int hh = h / 2; int t1 = (int) (w * 0.35); int t2 = (int) (w * 0.05); Point d = new Point(hw - t2, hh); Point e = new Point(hw + t2, hh); Point f = new Point(hw, hh - t1); Point g = new Point(hw, hh + t1); Path path = new Path(); path.setFillType(Path.FillType.EVEN_ODD); path.moveTo(d.x, d.y); path.lineTo(e.x, e.y); path.lineTo(f.x, f.y); path.close(); Path path2 = new Path(); path2.setFillType(Path.FillType.EVEN_ODD); path2.moveTo(d.x, d.y); path2.lineTo(e.x, e.y); path2.lineTo(g.x, g.y); path2.close(); arrowCanvas.drawPath(path, mCirclePaint); arrowCanvas.drawPath(path2, mWhiteArrowPaint); arrowCanvas.save(); } private void configureOrientation() { mDeviceOrientation = mDefaultDisplay.getRotation(); } private void startSensors() { boolean v1 = false; boolean v2 = false; boolean v3 = mSensorManager.registerListener(this, mRotationSensor, SensorManager.SENSOR_DELAY_GAME); if (v3) { mUseRotation = true; } else { v1 = mSensorManager.registerListener(this, mGravitySensor, SensorManager.SENSOR_DELAY_GAME); v2 = mSensorManager.registerListener(this, mMagneticSensor, SensorManager.SENSOR_DELAY_GAME); } if (v1 && v2) { mUseAccelerometer = true; mUseMagnetic = true; } mOrientationEventListener.enable(); } private void stopSensors() { mSensorManager.unregisterListener(this); mOrientationEventListener.disable(); } private void startUpdating() { if (mUpdater == null) mUpdater = new ElapsedUpdater(); if (!isUpdateTaskRunning) { mHandler.post(mUpdater); isUpdateTaskRunning = true; } } private void stopUpdating() { if (isUpdateTaskRunning) { mHandler.removeCallbacks(mUpdater); isUpdateTaskRunning = false; } } private void configureDeviceAngle() { switch (mDeviceOrientation) { case Surface.ROTATION_0: // Portrait SensorManager.remapCoordinateSystem(mRotation, SensorManager.AXIS_X, SensorManager.AXIS_Y, mRotationMapped); break; case Surface.ROTATION_90: // Landscape SensorManager.remapCoordinateSystem(mRotation, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_Z, mRotationMapped); break; case Surface.ROTATION_180: // Portrait SensorManager.remapCoordinateSystem(mRotation, SensorManager.AXIS_MINUS_X, SensorManager.AXIS_MINUS_Y, mRotationMapped); break; case Surface.ROTATION_270: // Landscape SensorManager.remapCoordinateSystem(mRotation, SensorManager.AXIS_MINUS_Y, SensorManager.AXIS_Z, mRotationMapped); break; } } private void loadSensorData(SensorEvent event) { int sensorType = event.sensor.getType(); if (sensorType == Sensor.TYPE_ACCELEROMETER) mGravity = event.values; if (sensorType == Sensor.TYPE_MAGNETIC_FIELD) mGeomagnetic = event.values; if (sensorType == Sensor.TYPE_ROTATION_VECTOR) mRotationVector = event.values; } @Override public void onSensorChanged(SensorEvent e) { loadSensorData(e); if (mUseRotation) { SensorManager.getRotationMatrixFromVector(mRotation, mRotationVector); } else if (mUseAccelerometer && mUseMagnetic) { SensorManager.getRotationMatrix(mRotation, null, mGravity, mGeomagnetic); } configureDeviceAngle(); SensorManager.getOrientation(mRotationMapped, mOrientation); float bearing = (float) Math.toDegrees(mOrientation[0]); if (bearing < 0) bearing += 360; mDirection = mAzimuth - bearing; mDirection = (mDirection < 0) ? mDirection + 360 : mDirection; } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } public void setAzimuth(float azimuth) { mAzimuth = azimuth; } private static int swapColor(int c1, int c2, float p) { float i = 1 - p; int r = (int) (Color.red(c1) * i + Color.red(c2) * p); int g = (int) (Color.green(c1) * i + Color.green(c2) * p); int b = (int) (Color.blue(c1) * i + Color.blue(c2) * p); return Color.argb(0xFF, r, g, b); } private static float calculateAngleDifference(float angle1, float angle2) { float diff = (angle2 - angle1 + 180) % 360 - 180; return diff < -180 ? diff + 360 : diff; } @Override protected void onDraw(Canvas canvas) { smoothDelta += (mDirectionDelta - smoothDelta) * 0.1; if (mDirection > 180) { smoothSweep += (-(360 - mDirection) - smoothSweep) * 0.2; } else { smoothSweep += (mDirection - smoothSweep) * 0.2; } canvas.drawArc(mArcCenterBounds, 270, smoothSweep, false, mArcPaint); updateOuterCirclePaint(getQiblaHintColorPercentage()); canvas.drawArc(mCircleInnerBounds, 0, 360, false, mOuterCirclePaint); mDirectionDelta = calculateAngleDifference(mLastDirection, mDirection); mArrowRotator.postRotate(smoothDelta, getWidth() / 2, getHeight() / 2); mLastDirection = mDirection; canvas.drawBitmap(mArrowBitmap, mArrowRotator, null); } @SuppressWarnings("SuspiciousNameCombination") @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int receivedWidth = MeasureSpec.getSize(widthMeasureSpec); int receivedHeight = MeasureSpec.getSize(heightMeasureSpec); if (receivedWidth < receivedHeight) { super.onMeasure(widthMeasureSpec, widthMeasureSpec); } else { super.onMeasure(heightMeasureSpec, heightMeasureSpec); } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { if (w != oldw || h != oldh) { initPaints(w, h); updateAzimuthArc(w, h); updateOuterCircle(w, h); initArrows(w, h); } super.onSizeChanged(w, h, oldw, oldh); invalidate(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); startSensors(); startUpdating(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); stopSensors(); stopUpdating(); } private float getQiblaHintColorPercentage() { float d = Math.abs(calculateAngleDifference(0, mDirection)); if (d < 2) { return 0; } else if (d < 7) { return d / 5 - 0.4f; } else { return 1; } } private void updateAzimuthArc(int w, int h) { final float thickness = w * THICKNESS_SCALE * 2; RectF arcOuterBounds = new RectF(0, 0, w, h); mArcInnerBounds = new RectF( arcOuterBounds.left + thickness, arcOuterBounds.top + thickness, arcOuterBounds.right - thickness, arcOuterBounds.bottom - thickness ); mArcCenterBounds = new RectF( arcOuterBounds.left + thickness / 2, arcOuterBounds.top + thickness / 2, arcOuterBounds.right - thickness / 2, arcOuterBounds.bottom - thickness / 2 ); } private void updateOuterCircle(int w, int h) { final float thickness = w * THICKNESS_SCALE; RectF circleOuterBounds = new RectF( mArcInnerBounds.left + thickness, mArcInnerBounds.top + thickness, mArcInnerBounds.right - thickness, mArcInnerBounds.bottom - thickness ); mCircleInnerBounds = new RectF( circleOuterBounds.left + thickness, circleOuterBounds.top + thickness, circleOuterBounds.right - thickness, circleOuterBounds.bottom - thickness ); } private class ElapsedUpdater implements Runnable { @Override public void run() { invalidate(); mHandler.postDelayed(this, 16); } } }
package com.nispok.snackbar; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.GradientDrawable; import android.os.Build; import android.support.annotation.AnimRes; import android.support.annotation.ColorRes; import android.support.annotation.StringRes; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AbsListView; import android.widget.FrameLayout; import android.widget.TextView; import com.nispok.snackbar.enums.SnackbarType; import com.nispok.snackbar.layouts.SnackbarLayout; import com.nispok.snackbar.listeners.ActionClickListener; import com.nispok.snackbar.listeners.EventListener; import com.nispok.snackbar.listeners.SwipeDismissTouchListener; /** * View that provides quick feedback about an operation in a small popup at the base of the screen */ public class Snackbar extends SnackbarLayout { public enum SnackbarDuration { LENGTH_SHORT(2000), LENGTH_LONG(3500); private long duration; SnackbarDuration(long duration) { this.duration = duration; } public long getDuration() { return duration; } } private SnackbarType mType = SnackbarType.SINGLE_LINE; private SnackbarDuration mDuration = SnackbarDuration.LENGTH_LONG; private CharSequence mText; private int mColor = -1; private int mTextColor = -1; private int mOffset; private long mSnackbarStart; private long mSnackbarFinish; private long mTimeRemaining = -1; private CharSequence mActionLabel; private int mActionColor = -1; private boolean mAnimated = true; private long mCustomDuration = -1; private ActionClickListener mActionClickListener; private boolean mShouldDismissOnActionClicked = true; private EventListener mEventListener; private boolean mIsShowing = false; private boolean mCanSwipeToDismiss = true; private boolean mIsDismissing = false; private Runnable mDismissRunnable = new Runnable() { @Override public void run() { dismiss(); } }; private Snackbar(Context context) { super(context); } public static Snackbar with(Context context) { return new Snackbar(context); } /** * Sets the type of {@link Snackbar} to be displayed. * * @param type the {@link SnackbarType} of this instance * @return */ public Snackbar type(SnackbarType type) { mType = type; return this; } /** * Sets the text to be displayed in this {@link Snackbar} * * @param text * @return */ public Snackbar text(CharSequence text) { mText = text; return this; } /** * Sets the text to be displayed in this {@link Snackbar} * * @param resId * @return */ public Snackbar text(@StringRes int resId) { return text(getContext().getText(resId)); } /** * Sets the background color of this {@link Snackbar} * * @param color * @return */ public Snackbar color(int color) { mColor = color; return this; } /** * Sets the background color of this {@link Snackbar} * * @param resId * @return */ public Snackbar colorResource(@ColorRes int resId) { return color(getResources().getColor(resId)); } /** * Sets the text color of this {@link Snackbar} * * @param textColor * @return */ public Snackbar textColor(int textColor) { mTextColor = textColor; return this; } /** * Sets the text color of this {@link Snackbar} * * @param resId * @return */ public Snackbar textColorResource(@ColorRes int resId) { return textColor(getResources().getColor(resId)); } /** * Sets the action label to be displayed, if any. Note that if this is not set, the action * button will not be displayed * * @param actionButtonLabel * @return */ public Snackbar actionLabel(CharSequence actionButtonLabel) { mActionLabel = actionButtonLabel; return this; } /** * Sets the action label to be displayed, if any. Note that if this is not set, the action * button will not be displayed * * @param resId * @return */ public Snackbar actionLabel(@StringRes int resId) { return actionLabel(getContext().getString(resId)); } /** * Sets the color of the action button label. Note that you must set a button label with * {@link Snackbar#actionLabel(CharSequence)} for this button to be displayed * * @param actionColor * @return */ public Snackbar actionColor(int actionColor) { mActionColor = actionColor; return this; } /** * Sets the color of the action button label. Note that you must set a button label with * {@link Snackbar#actionLabel(CharSequence)} for this button to be displayed * * @param resId * @return */ public Snackbar actionColorResource(@ColorRes int resId) { return actionColor(getResources().getColor(resId)); } /** * Determines whether this {@link Snackbar} should dismiss when the action button is touched * * @param shouldDismiss * @return */ public Snackbar dismissOnActionClicked(boolean shouldDismiss) { mShouldDismissOnActionClicked = shouldDismiss; return this; } /** * Sets the listener to be called when the {@link Snackbar} action is * selected. Note that you must set a button label with * {@link Snackbar#actionLabel(CharSequence)} for this button to be displayed * * @param listener * @return */ public Snackbar actionListener(ActionClickListener listener) { mActionClickListener = listener; return this; } /** * Sets the listener to be called when the {@link Snackbar} is dismissed. * * @param listener * @return */ public Snackbar eventListener(EventListener listener) { mEventListener = listener; return this; } /** * Sets on/off animation for this {@link Snackbar} * * @param withAnimation * @return */ public Snackbar animation(boolean withAnimation) { mAnimated = withAnimation; return this; } /** * Determines whether this {@link com.nispok.snackbar.Snackbar} can be swiped off from the screen * * @param canSwipeToDismiss * @return */ public Snackbar swipeToDismiss(boolean canSwipeToDismiss) { mCanSwipeToDismiss = canSwipeToDismiss; return this; } /** * Sets the duration of this {@link Snackbar}. See * {@link Snackbar.SnackbarDuration} for available options * * @param duration * @return */ public Snackbar duration(SnackbarDuration duration) { mDuration = duration; return this; } /** * Sets a custom duration of this {@link Snackbar} * * @param duration * @return */ public Snackbar duration(long duration) { mCustomDuration = duration; return this; } /** * Attaches this {@link Snackbar} to an AbsListView (ListView, GridView, ExpandableListView) so * it dismisses when the list is scrolled * * @param absListView * @return */ public Snackbar attachToAbsListView(AbsListView absListView) { absListView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { dismiss(); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }); return this; } /** * Attaches this {@link Snackbar} to a RecyclerView so it dismisses when the list is scrolled * * @param recyclerView * @return */ public Snackbar attachToRecyclerView(RecyclerView recyclerView) { recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); dismiss(); } }); return this; } private FrameLayout.LayoutParams init(Activity parent) { SnackbarLayout layout = (SnackbarLayout) LayoutInflater.from(parent) .inflate(R.layout.sb__template, this, true); Resources res = getResources(); mColor = mColor != -1 ? mColor : res.getColor(R.color.sb__background); mOffset = res.getDimensionPixelOffset(R.dimen.sb__offset); float scale = res.getDisplayMetrics().density; FrameLayout.LayoutParams params; if (res.getBoolean(R.bool.is_phone)) { // Phone layout.setMinimumHeight(dpToPx(mType.getMinHeight(), scale)); layout.setMaxHeight(dpToPx(mType.getMaxHeight(), scale)); layout.setBackgroundColor(mColor); params = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT); } else { // Tablet/desktop mType = SnackbarType.SINGLE_LINE; // Force single-line layout.setMinimumWidth(res.getDimensionPixelSize(R.dimen.sb__min_width)); layout.setMaxWidth(res.getDimensionPixelSize(R.dimen.sb__max_width)); layout.setBackgroundResource(R.drawable.sb__bg); GradientDrawable bg = (GradientDrawable) layout.getBackground(); bg.setColor(mColor); params = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, dpToPx(mType.getMaxHeight(), scale)); params.leftMargin = mOffset; params.bottomMargin = mOffset; } params.gravity = Gravity.BOTTOM; TextView snackbarText = (TextView) layout.findViewById(R.id.sb__text); snackbarText.setText(mText); if (mTextColor != -1) { snackbarText.setTextColor(mTextColor); } snackbarText.setMaxLines(mType.getMaxLines()); TextView snackbarAction = (TextView) layout.findViewById(R.id.sb__action); if (!TextUtils.isEmpty(mActionLabel)) { requestLayout(); snackbarAction.setText(mActionLabel); if (mActionColor != -1) { snackbarAction.setTextColor(mActionColor); } snackbarAction.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (mActionClickListener != null) { mActionClickListener.onActionClicked(Snackbar.this); } if (mShouldDismissOnActionClicked) { dismiss(); } } }); snackbarAction.setMaxLines(mType.getMaxLines()); } else { snackbarAction.setVisibility(GONE); } setClickable(true); if (mCanSwipeToDismiss && res.getBoolean(R.bool.is_swipeable)) { setOnTouchListener(new SwipeDismissTouchListener(this, null, new SwipeDismissTouchListener.DismissCallbacks() { @Override public boolean canDismiss(Object token) { return true; } @Override public void onDismiss(View view, Object token) { if (view != null) { dismiss(false); } } @Override public void pauseTimer(boolean shouldPause) { if (shouldPause) { removeCallbacks(mDismissRunnable); mSnackbarFinish = System.currentTimeMillis(); } else { mTimeRemaining -= (mSnackbarFinish - mSnackbarStart); startTimer(mTimeRemaining); } } })); } return params; } private static int dpToPx(int dp, float scale) { return (int) (dp * scale + 0.5f); } /** * Displays the {@link Snackbar} at the bottom of the * {@link android.app.Activity} provided. * * @param targetActivity */ public void show(Activity targetActivity) { FrameLayout.LayoutParams params = init(targetActivity); ViewGroup root = (ViewGroup) targetActivity.findViewById(android.R.id.content); if (root.getMeasuredHeight() == root.getBottom()) { Resources resources = targetActivity.getResources(); int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { params.bottomMargin = resources.getDimensionPixelSize(resourceId); } } root.addView(this, params); bringToFront(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { root.requestLayout(); root.invalidate(); } mIsShowing = true; getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { getViewTreeObserver().removeOnPreDrawListener(this); if (mEventListener != null) { mEventListener.onShow(Snackbar.this); if (!mAnimated) { mEventListener.onShown(Snackbar.this); } } return true; } }); if (!mAnimated) { startTimer(); return; } Animation slideIn = AnimationUtils.loadAnimation(getContext(), R.anim.snackbar_in); slideIn.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { if (mEventListener != null) { mEventListener.onShown(Snackbar.this); } post(new Runnable() { @Override public void run() { mSnackbarStart = System.currentTimeMillis(); if (mTimeRemaining == -1) { mTimeRemaining = getDuration(); } startTimer(); } }); } @Override public void onAnimationRepeat(Animation animation) { } }); startAnimation(slideIn); } private void startTimer() { postDelayed(mDismissRunnable, getDuration()); } private void startTimer(long duration) { postDelayed(mDismissRunnable, duration); } public void dismiss() { dismiss(mAnimated); } private void dismiss(boolean animate) { if (mIsDismissing) { return; } mIsDismissing = true; if (mEventListener != null && mIsShowing) { mEventListener.onDismiss(Snackbar.this); } if (!animate) { finish(); return; } final Animation slideOut = AnimationUtils.loadAnimation(getContext(), R.anim.snackbar_out); slideOut.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { post(new Runnable() { @Override public void run() { finish(); } }); } @Override public void onAnimationRepeat(Animation animation) { } }); startAnimation(slideOut); } private void finish() { clearAnimation(); ViewGroup parent = (ViewGroup) getParent(); if (parent != null) { parent.removeView(this); } if (mEventListener != null && mIsShowing) { mEventListener.onDismissed(this); } mIsShowing = false; } public int getActionColor() { return mActionColor; } public CharSequence getActionLabel() { return mActionLabel; } public int getTextColor() { return mTextColor; } public int getColor() { return mColor; } public CharSequence getText() { return mText; } public long getDuration() { return mCustomDuration == -1 ? mDuration.getDuration() : mCustomDuration; } public SnackbarType getType() { return mType; } /** * @return the pixel offset of this {@link com.nispok.snackbar.Snackbar} from the left and * bottom of the {@link android.app.Activity}. */ public int getOffset() { return mOffset; } public boolean isAnimated() { return mAnimated; } public boolean shouldDismissOnActionClicked() { return mShouldDismissOnActionClicked; } /** * @return true if this {@link com.nispok.snackbar.Snackbar} is currently showing */ public boolean isShowing() { return mIsShowing; } /** * @return false if this {@link com.nispok.snackbar.Snackbar} has been dismissed */ public boolean isDismissed() { return !mIsShowing; } /** * @return the animation resource used by this {@link com.nispok.snackbar.Snackbar} instance * to enter the view */ @AnimRes public static int getInAnimationResource() { return R.anim.snackbar_in; } /** * @return the animation resource used by this {@link com.nispok.snackbar.Snackbar} instance * to exit the view */ @AnimRes public static int getOutAnimationResource() { return R.anim.snackbar_out; } }
/* The following code was generated by JFlex 1.4 on 4/6/05 3:49 PM */ /* It's an automatically generated code. Do not modify it. */ package com.intellij.lexer; import com.intellij.psi.tree.IElementType; import com.intellij.psi.*; import com.intellij.psi.xml.*; public class _HtmlLexer implements FlexLexer { /** initial size of the lookahead buffer */ private static final int ZZ_BUFFERSIZE = 16384; /** lexical states */ public static final int PROCESSING_INSTRUCTION = 9; public static final int END_TAG_NAME = 4; public static final int START_TAG_NAME = 3; public static final int ATTRIBUTE_VALUE_SQ = 8; public static final int DOC_TYPE = 1; public static final int ATTRIBUTE_VALUE_DQ = 7; public static final int YYINITIAL = 0; public static final int TAG_ATTRIBUTES = 5; public static final int COMMENT = 2; public static final int ATTRIBUTE_VALUE_START = 6; /** * Translates characters to character classes */ private static final String ZZ_CMAP_PACKED = "\11\0\2\3\1\0\2\3\22\0\1\3\1\11\1\6\4\0\1\7"+ "\5\0\1\4\1\2\1\31\12\2\1\1\1\0\1\10\1\32\1\30"+ "\1\27\1\0\1\1\1\25\1\14\1\12\1\20\2\1\1\21\1\26"+ "\2\1\1\23\1\22\1\1\1\13\1\17\3\1\1\15\1\24\3\1"+ "\1\16\1\1\1\0\1\5\2\0\1\1\1\0\1\1\1\25\1\14"+ "\1\12\1\20\2\1\1\21\1\26\2\1\1\23\1\22\1\1\1\13"+ "\1\17\3\1\1\15\1\24\3\1\1\16\1\1\57\0\1\1\12\0"+ "\1\1\4\0\1\1\5\0\27\1\1\0\37\1\1\0\u0128\1\2\0"+ "\22\1\34\0\136\1\2\0\11\1\2\0\7\1\16\0\2\1\16\0"+ "\5\1\11\0\1\1\213\0\1\1\13\0\1\1\1\0\3\1\1\0"+ "\1\1\1\0\24\1\1\0\54\1\1\0\10\1\2\0\32\1\14\0"+ "\202\1\12\0\71\1\2\0\2\1\2\0\2\1\3\0\46\1\2\0"+ "\2\1\67\0\46\1\2\0\1\1\7\0\47\1\110\0\33\1\5\0"+ "\3\1\56\0\32\1\5\0\13\1\46\0\143\1\1\0\1\1\17\0"+ "\2\1\23\0\3\1\23\0\1\1\1\0\33\1\123\0\46\1\u015f\0"+ "\65\1\3\0\1\1\22\0\1\1\7\0\12\1\43\0\10\1\2\0"+ "\2\1\2\0\26\1\1\0\7\1\1\0\1\1\3\0\4\1\42\0"+ "\2\1\1\0\3\1\16\0\2\1\23\0\6\1\4\0\2\1\2\0"+ "\26\1\1\0\7\1\1\0\2\1\1\0\2\1\1\0\2\1\37\0"+ "\4\1\1\0\1\1\23\0\3\1\20\0\7\1\1\0\1\1\1\0"+ "\3\1\1\0\26\1\1\0\7\1\1\0\2\1\1\0\5\1\3\0"+ "\1\1\22\0\1\1\17\0\1\1\44\0\10\1\2\0\2\1\2\0"+ "\26\1\1\0\7\1\1\0\2\1\2\0\4\1\3\0\1\1\36\0"+ "\2\1\1\0\3\1\43\0\6\1\3\0\3\1\1\0\4\1\3\0"+ "\2\1\1\0\1\1\1\0\2\1\3\0\2\1\3\0\3\1\3\0"+ "\10\1\1\0\3\1\113\0\10\1\1\0\3\1\1\0\27\1\1\0"+ "\12\1\1\0\5\1\46\0\2\1\43\0\10\1\1\0\3\1\1\0"+ "\27\1\1\0\12\1\1\0\5\1\44\0\1\1\1\0\2\1\43\0"+ "\10\1\1\0\3\1\1\0\27\1\1\0\20\1\46\0\2\1\43\0"+ "\22\1\3\0\30\1\1\0\11\1\1\0\1\1\2\0\7\1\72\0"+ "\60\1\1\0\2\1\14\0\7\1\72\0\2\1\1\0\1\1\2\0"+ "\2\1\1\0\1\1\2\0\1\1\6\0\4\1\1\0\7\1\1\0"+ "\3\1\1\0\1\1\1\0\1\1\2\0\2\1\1\0\4\1\1\0"+ "\2\1\11\0\1\1\2\0\5\1\1\0\1\1\25\0\2\1\42\0"+ "\1\1\77\0\10\1\1\0\42\1\35\0\4\1\164\0\42\1\1\0"+ "\5\1\1\0\2\1\45\0\6\1\112\0\46\1\12\0\47\1\11\0"+ "\132\1\5\0\104\1\5\0\122\1\6\0\7\1\1\0\77\1\1\0"+ "\1\1\1\0\4\1\2\0\7\1\1\0\1\1\1\0\4\1\2\0"+ "\47\1\1\0\1\1\1\0\4\1\2\0\37\1\1\0\1\1\1\0"+ "\4\1\2\0\7\1\1\0\1\1\1\0\4\1\2\0\7\1\1\0"+ "\7\1\1\0\27\1\1\0\37\1\1\0\1\1\1\0\4\1\2\0"+ "\7\1\1\0\47\1\1\0\23\1\105\0\125\1\14\0\u026c\1\2\0"+ "\10\1\12\0\32\1\5\0\113\1\225\0\64\1\154\0\130\1\10\0"+ "\51\1\u0557\0\234\1\4\0\132\1\6\0\26\1\2\0\6\1\2\0"+ "\46\1\2\0\6\1\2\0\10\1\1\0\1\1\1\0\1\1\1\0"+ "\1\1\1\0\37\1\2\0\65\1\1\0\7\1\1\0\1\1\3\0"+ "\3\1\1\0\7\1\3\0\4\1\2\0\6\1\4\0\15\1\5\0"+ "\3\1\1\0\7\1\202\0\1\1\202\0\1\1\4\0\1\1\2\0"+ "\12\1\1\0\1\1\3\0\5\1\6\0\1\1\1\0\1\1\1\0"+ "\1\1\1\0\4\1\1\0\3\1\1\0\7\1\u0ecb\0\2\1\52\0"+ "\5\1\13\0\124\1\10\0\2\1\2\0\132\1\1\0\3\1\6\0"+ "\50\1\4\0\136\1\21\0\30\1\u0248\0\u19b6\1\112\0\u51a6\1\132\0"+ "\u048d\1\u0773\0\u2ba4\1\u215c\0\u012e\1\322\0\7\1\14\0\5\1\5\0"+ "\1\1\1\0\12\1\1\0\15\1\1\0\5\1\1\0\1\1\1\0"+ "\2\1\1\0\2\1\1\0\154\1\41\0\u016b\1\22\0\100\1\2\0"+ "\66\1\50\0\14\1\164\0\3\1\1\0\1\1\1\0\207\1\44\0"+ "\32\1\6\0\32\1\13\0\131\1\3\0\6\1\2\0\6\1\2\0"+ "\6\1\2\0\3\1\43\0"; /** * Translates characters to character classes */ private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); /** * Translates DFA states to action switch labels. */ private static final int [] ZZ_ACTION = zzUnpackAction(); private static final String ZZ_ACTION_PACKED_0 = "\2\0\1\1\3\0\1\2\2\3\1\4\1\5\1\6"+ "\1\7\5\10\1\11\1\1\1\10\1\12\1\13\1\14"+ "\1\15\1\13\1\16\1\2\1\17\1\20\1\10\2\3"+ "\1\21\2\3\1\4\1\10\1\22\1\0\1\23\1\24"+ "\1\0\1\3\5\0\1\25\6\0\1\26\1\27\2\0"+ "\1\14\3\0\1\30\2\0\1\31"; private static int [] zzUnpackAction() { int [] result = new int[68]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; } private static int zzUnpackAction(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** * Translates a state to a row index in the transition table */ private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); private static final String ZZ_ROWMAP_PACKED_0 = "\0\0\0\33\0\66\0\121\0\154\0\207\0\242\0\275"+ "\0\330\0\363\0\u010e\0\u0129\0\u0144\0\u010e\0\u015f\0\u017a"+ "\0\u0195\0\u01b0\0\u010e\0\u01cb\0\u01e6\0\u0201\0\u010e\0\u021c"+ "\0\u010e\0\u0237\0\u010e\0\u0252\0\u010e\0\u010e\0\u0237\0\u026d"+ "\0\u0288\0\u010e\0\u02a3\0\u02be\0\u02d9\0\u02f4\0\u010e\0\u030f"+ "\0\u010e\0\u010e\0\u015f\0\u010e\0\u017a\0\u032a\0\u0345\0\u0360"+ "\0\u037b\0\u010e\0\u0396\0\u03b1\0\u03cc\0\u03e7\0\u0402\0\u041d"+ "\0\u010e\0\u010e\0\u0438\0\u0453\0\u010e\0\u046e\0\u0489\0\u04a4"+ "\0\u010e\0\u04bf\0\u04da\0\u010e"; private static int [] zzUnpackRowMap() { int [] result = new int[68]; int offset = 0; offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); return result; } private static int zzUnpackRowMap(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int high = packed.charAt(i++) << 16; result[j++] = high | packed.charAt(i++); } return j; } /** * The transition table of the DFA */ private static final int [] ZZ_TRANS = zzUnpackTrans(); private static final String ZZ_TRANS_PACKED_0 = "\3\13\1\14\4\13\1\15\22\13\3\16\1\14\2\16"+ "\1\17\1\20\7\16\1\21\1\16\1\22\6\16\1\23"+ "\2\16\4\24\1\25\26\24\1\16\1\26\10\16\15\26"+ "\5\16\1\26\6\16\1\27\1\16\15\26\4\16\1\27"+ "\1\30\1\27\1\14\6\27\15\30\1\27\1\31\1\32"+ "\1\33\3\34\1\14\2\34\1\35\1\36\20\34\1\31"+ "\1\37\1\34\5\40\1\41\1\42\24\40\5\43\1\44"+ "\1\43\1\42\23\43\27\45\1\46\1\47\2\45\36\0"+ "\1\14\40\0\1\50\15\0\1\51\1\0\1\52\1\0"+ "\6\53\1\54\24\53\7\55\1\54\23\55\24\0\1\56"+ "\23\0\1\57\15\0\4\24\1\60\32\24\1\61\26\24"+ "\1\0\2\26\1\0\1\26\5\0\15\26\5\0\2\30"+ "\1\0\1\30\5\0\15\30\34\0\1\62\2\0\3\34"+ "\1\0\2\34\2\0\20\34\2\0\1\34\5\40\1\41"+ "\1\0\31\40\1\41\25\40\5\43\1\44\1\43\1\0"+ "\30\43\1\44\25\43\27\45\1\63\1\0\32\45\1\47"+ "\2\45\4\0\1\64\5\0\1\65\45\0\1\66\27\0"+ "\1\67\10\0\4\24\1\70\33\24\1\0\22\24\1\71"+ "\2\24\30\45\1\0\2\45\4\0\1\72\41\0\1\73"+ "\42\0\1\74\32\0\1\75\7\0\5\24\1\0\22\24"+ "\1\0\2\24\14\0\1\76\44\0\1\77\21\0\1\100"+ "\31\0\1\101\34\0\1\102\33\0\1\103\33\0\1\104"+ "\12\0"; private static int [] zzUnpackTrans() { int [] result = new int[1269]; int offset = 0; offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); return result; } private static int zzUnpackTrans(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); value do result[j++] = value; while (--count > 0); } return j; } /* error codes */ private static final int ZZ_UNKNOWN_ERROR = 0; private static final int ZZ_NO_MATCH = 1; private static final int ZZ_PUSHBACK_2BIG = 2; private static final char[] EMPTY_BUFFER = new char[0]; private static final int YYEOF = -1; private static java.io.Reader zzReader = null; // Fake /* error messages for the codes above */ private static final String ZZ_ERROR_MSG[] = { "Unkown internal scanner error", "Error: could not match input", "Error: pushback value was too large" }; /** * ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code> */ private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); private static final String ZZ_ATTRIBUTE_PACKED_0 = "\2\0\1\1\3\0\4\1\1\11\2\1\1\11\4\1"+ "\1\11\3\1\1\11\1\1\1\11\1\1\1\11\1\1"+ "\2\11\3\1\1\11\4\1\1\11\1\0\2\11\1\0"+ "\1\11\5\0\1\11\6\0\2\11\2\0\1\11\3\0"+ "\1\11\2\0\1\11"; private static int [] zzUnpackAttribute() { int [] result = new int[68]; int offset = 0; offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; } private static int zzUnpackAttribute(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** the current state of the DFA */ private int zzState; /** the current lexical state */ private int zzLexicalState = YYINITIAL; /** this buffer contains the current text to be matched and is the source of the yytext() string */ private CharSequence zzBuffer = ""; /** the textposition at the last accepting state */ private int zzMarkedPos; /** the textposition at the last state to be included in yytext */ private int zzPushbackPos; /** the current text position in the buffer */ private int zzCurrentPos; /** startRead marks the beginning of the yytext() string in the buffer */ private int zzStartRead; /** endRead marks the last character in the buffer, that has been read from input */ private int zzEndRead; /** * zzAtBOL == true <=> the scanner is currently at the beginning of a line */ private boolean zzAtBOL = true; /** zzAtEOF == true <=> the scanner is at the EOF */ private boolean zzAtEOF; /** denotes if the user-EOF-code has already been executed */ private boolean zzEOFDone; /* user code: */ public _HtmlLexer() { this((java.io.Reader)null); } public _HtmlLexer(java.io.Reader in) { this.zzReader = in; } /** * Creates a new scanner. * There is also java.io.Reader version of this constructor. * * @param in the java.io.Inputstream to read input from. */ public _HtmlLexer(java.io.InputStream in) { this(new java.io.InputStreamReader(in)); } /** * Unpacks the compressed character translation table. * * @param packed the packed character translation table * @return the unpacked character translation table */ private static char [] zzUnpackCMap(String packed) { char [] map = new char[0x10000]; int i = 0; /* index in packed string */ int j = 0; /* index in unpacked array */ while (i < 1148) { int count = packed.charAt(i++); char value = packed.charAt(i++); do map[j++] = value; while (--count > 0); } return map; } public final int getTokenStart(){ return zzStartRead - zzPushbackPos; } public final int getTokenEnd(){ return getTokenStart() + yylength(); } public void reset(CharSequence buffer, int initialState){ zzBuffer = buffer; zzCurrentPos = zzMarkedPos = zzStartRead = 0; zzPushbackPos = 0; zzAtEOF = false; zzEndRead = buffer.length(); yybegin(initialState); } /** * Refills the input buffer. * * @return <code>false</code>, iff there was new input. * * @exception java.io.IOException if any I/O-Error occurs */ private boolean zzRefill() throws java.io.IOException { return true; } /** * Returns the current lexical state. */ public final int yystate() { return zzLexicalState; } /** * Enters a new lexical state * * @param newState the new lexical state */ public final void yybegin(int newState) { zzLexicalState = newState; } /** * Returns the text matched by the current regular expression. */ public final CharSequence yytext() { return zzBuffer.subSequence(zzStartRead, zzMarkedPos); } /** * Returns the character at position <tt>pos</tt> from the * matched text. * * It is equivalent to yytext().charAt(pos), but faster * * @param pos the position of the character to fetch. * A value from 0 to yylength()-1. * * @return the character at position pos */ public final char yycharat(int pos) { return zzBuffer.charAt(zzStartRead+pos); } /** * Returns the length of the matched text region. */ public final int yylength() { return zzMarkedPos-zzStartRead; } /** * Reports an error that occured while scanning. * * In a wellformed scanner (no or only correct usage of * yypushback(int) and a match-all fallback rule) this method * will only be called with things that "Can't Possibly Happen". * If this method is called, something is seriously wrong * (e.g. a JFlex bug producing a faulty scanner etc.). * * Usual syntax/scanner level error handling should be done * in error fallback rules. * * @param errorCode the code of the errormessage to display */ private void zzScanError(int errorCode) { String message; try { message = ZZ_ERROR_MSG[errorCode]; } catch (ArrayIndexOutOfBoundsException e) { message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; } throw new Error(message); } /** * Pushes the specified amount of characters back into the input stream. * * They will be read again by then next call of the scanning method * * @param number the number of characters to be read again. * This number must not be greater than yylength()! */ public void yypushback(int number) { if ( number > yylength() ) zzScanError(ZZ_PUSHBACK_2BIG); zzMarkedPos -= number; } /** * Contains user EOF-code, which will be executed exactly once, * when the end of file is reached */ private void zzDoEOF() { if (!zzEOFDone) { zzEOFDone = true; } } /** * Resumes scanning until the next regular expression is matched, * the end of input is encountered or an I/O-Error occurs. * * @return the next token * @exception java.io.IOException if any I/O-Error occurs */ public IElementType advance() throws java.io.IOException { int zzInput; int zzAction; // cached fields: int zzCurrentPosL; int zzMarkedPosL; int zzEndReadL = zzEndRead; CharSequence zzBufferL = zzBuffer; char [] zzCMapL = ZZ_CMAP; int [] zzTransL = ZZ_TRANS; int [] zzRowMapL = ZZ_ROWMAP; int [] zzAttrL = ZZ_ATTRIBUTE; while (true) { zzMarkedPosL = zzMarkedPos; zzAction = -1; zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; zzState = zzLexicalState; zzForAction: { while (true) { if (zzCurrentPosL < zzEndReadL) zzInput = zzBufferL.charAt(zzCurrentPosL++); else if (zzAtEOF) { zzInput = YYEOF; break zzForAction; } else { // store back cached positions zzCurrentPos = zzCurrentPosL; zzMarkedPos = zzMarkedPosL; boolean eof = zzRefill(); // get translated positions and possibly new buffer zzCurrentPosL = zzCurrentPos; zzMarkedPosL = zzMarkedPos; zzBufferL = zzBuffer; zzEndReadL = zzEndRead; if (eof) { zzInput = YYEOF; break zzForAction; } else { zzInput = zzBufferL.charAt(zzCurrentPosL++); } } int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; if (zzNext == -1) break zzForAction; zzState = zzNext; int zzAttributes = zzAttrL[zzState]; if ( (zzAttributes & 1) == 1 ) { zzAction = zzState; zzMarkedPosL = zzCurrentPosL; if ( (zzAttributes & 8) == 8 ) break zzForAction; } } } // store back cached position zzMarkedPos = zzMarkedPosL; switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { case 3: { return XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN; } case 26: break; case 8: { return XmlTokenType.XML_BAD_CHARACTER; } case 27: break; case 11: { yybegin(YYINITIAL); yypushback(1); break; } case 28: break; case 15: { yybegin(ATTRIBUTE_VALUE_DQ); return XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER; } case 29: break; case 24: { return XmlTokenType.XML_DOCTYPE_PUBLIC; } case 30: break; case 25: { yybegin(DOC_TYPE); return XmlTokenType.XML_DOCTYPE_START; } case 31: break; case 4: { return XmlTokenType.XML_PI_TARGET; } case 32: break; case 21: { yybegin(YYINITIAL); return XmlTokenType.XML_EMPTY_ELEMENT_END; } case 33: break; case 18: { yybegin(YYINITIAL); return XmlTokenType.XML_PI_END; } case 34: break; case 17: { yybegin(TAG_ATTRIBUTES); return XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER; } case 35: break; case 23: { yybegin(COMMENT); return XmlTokenType.XML_COMMENT_START; } case 36: break; case 2: { yybegin(TAG_ATTRIBUTES); return XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN; } case 37: break; case 1: { return XmlTokenType.XML_COMMENT_CHARACTERS; } case 38: break; case 14: { yybegin(ATTRIBUTE_VALUE_START); return XmlTokenType.XML_EQ; } case 39: break; case 20: { yybegin(END_TAG_NAME); return XmlTokenType.XML_END_TAG_START; } case 40: break; case 9: { yybegin(YYINITIAL); return XmlTokenType.XML_DOCTYPE_END; } case 41: break; case 16: { yybegin(ATTRIBUTE_VALUE_SQ); return XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER; } case 42: break; case 7: { yybegin(START_TAG_NAME); return XmlTokenType.XML_START_TAG_START; } case 43: break; case 12: { return XmlTokenType.XML_NAME; } case 44: break; case 13: { yybegin(YYINITIAL); return XmlTokenType.XML_TAG_END; } case 45: break; case 22: { yybegin(YYINITIAL); return XmlTokenType.XML_COMMENT_END; } case 46: break; case 10: { yybegin(TAG_ATTRIBUTES); return XmlTokenType.XML_NAME; } case 47: break; case 19: { yybegin(PROCESSING_INSTRUCTION); return XmlTokenType.XML_PI_START; } case 48: break; case 6: { return XmlTokenType.XML_WHITE_SPACE; } case 49: break; case 5: { return XmlTokenType.XML_DATA_CHARACTERS; } case 50: break; default: if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true; zzDoEOF(); return null; } else { zzScanError(ZZ_NO_MATCH); } } } } }
package com.exedio.cope.lib; import java.io.ByteArrayInputStream; import java.io.IOException; public class AttributesTest extends DatabaseLibTest { private ItemWithoutAttributes someItem, someItem2; private ItemWithManyAttributes item; public void setUp() throws Exception { super.setUp(); someItem = new ItemWithoutAttributes(); someItem2 = new ItemWithoutAttributes(); item = new ItemWithManyAttributes("someString", 5, 2.2, true, someItem, ItemWithManyAttributes.SomeEnumeration.enumValue1); } public void tearDown() throws Exception { item.delete(); item = null; someItem.delete(); someItem = null; someItem2.delete(); someItem2 = null; super.tearDown(); } public void testSomeString() { assertEquals(item.TYPE, item.someString.getType()); assertEquals(item.TYPE, item.someStringUpperCase.getType()); assertEquals(null, item.getSomeString()); assertEquals(null, item.getSomeStringUpperCase()); item.setSomeString("someString"); assertEquals("someString", item.getSomeString()); assertEquals("SOMESTRING", item.getSomeStringUpperCase()); assertEquals( set(item), toSet( Search.search( item.TYPE, Search.equal(item.someString, "someString")))); assertEquals( set(), toSet( Search.search( item.TYPE, Search.equal(item.someString, "SOMESTRING")))); assertEquals( set(item), toSet( Search.search( item.TYPE, Search.equal(item.someStringUpperCase, "SOMESTRING")))); assertEquals( set(), toSet( Search.search( item.TYPE, Search.equal(item.someStringUpperCase, "someString")))); item.passivate(); assertEquals("someString", item.getSomeString()); assertEquals("SOMESTRING", item.getSomeStringUpperCase()); item.setSomeString(null); assertEquals(null, item.getSomeString()); assertEquals(null, item.getSomeStringUpperCase()); } public void testSomeNotNullString() { assertEquals(item.TYPE, item.someNotNullString.getType()); assertEquals("someString", item.getSomeNotNullString()); try { item.setSomeNotNullString("someOtherString"); } catch (NotNullViolationException e) { throw new SystemException(e); } assertEquals("someOtherString", item.getSomeNotNullString()); try { item.setSomeNotNullString(null); fail("should have thrown NotNullViolationException"); } catch (NotNullViolationException e) { assertEquals(item.someNotNullString, e.getNotNullAttribute()); assertEquals(item, e.getItem()); } try { new ItemWithManyAttributes(null, 5, 2.2, true, someItem, ItemWithManyAttributes.SomeEnumeration.enumValue1); fail("should have thrown NotNullViolationException"); } catch(NotNullViolationException e) { assertEquals(null, e.getItem()); assertEquals(item.someNotNullString, e.getNotNullAttribute()); } } public void testSomeInteger() { assertEquals(item.TYPE, item.someInteger.getType()); assertEquals(null, item.getSomeInteger()); assertEquals(list(item), Search.search(item.TYPE, Search.equal(item.someInteger, null))); assertEquals(list(item), Search.search(item.TYPE, Search.isNull(item.someInteger))); item.setSomeInteger(new Integer(10)); assertEquals(new Integer(10), item.getSomeInteger()); item.passivate(); assertEquals(new Integer(10), item.getSomeInteger()); assertEquals( list(item), Search.search(item.TYPE, Search.equal(item.someInteger, 10))); assertEquals(list(), Search.search(item.TYPE, Search.equal(item.someInteger, null))); assertEquals(list(), Search.search(item.TYPE, Search.isNull(item.someInteger))); item.setSomeInteger(null); assertEquals(null, item.getSomeInteger()); item.passivate(); assertEquals(null, item.getSomeInteger()); } public void testSomeNotNullInteger() { assertEquals(item.TYPE, item.someNotNullInteger.getType()); assertEquals(5, item.getSomeNotNullInteger()); item.setSomeNotNullInteger(20); assertEquals(20, item.getSomeNotNullInteger()); item.setSomeNotNullInteger(0); assertEquals(0, item.getSomeNotNullInteger()); item.passivate(); assertEquals(0, item.getSomeNotNullInteger()); assertEquals( set(item), toSet( Search.search( item.TYPE, Search.equal(item.someNotNullInteger, 0)))); item.setSomeNotNullInteger(Integer.MIN_VALUE); assertEquals(Integer.MIN_VALUE, item.getSomeNotNullInteger()); item.passivate(); assertEquals(Integer.MIN_VALUE, item.getSomeNotNullInteger()); assertEquals( set(item), toSet( Search.search( item.TYPE, Search.equal(item.someNotNullInteger, Integer.MIN_VALUE)))); item.setSomeNotNullInteger(Integer.MAX_VALUE); assertEquals(Integer.MAX_VALUE, item.getSomeNotNullInteger()); item.passivate(); assertEquals(Integer.MAX_VALUE, item.getSomeNotNullInteger()); assertEquals( set(item), toSet( Search.search( item.TYPE, Search.equal(item.someNotNullInteger, Integer.MAX_VALUE)))); } public void testSomeDouble() { assertEquals(item.TYPE, item.someDouble.getType()); assertEquals(null, item.getSomeDouble()); assertEquals(list(item), Search.search(item.TYPE, Search.equal(item.someDouble, null))); assertEquals(list(item), Search.search(item.TYPE, Search.isNull(item.someDouble))); item.setSomeDouble(new Double(22.22)); assertEquals(new Double(22.22), item.getSomeDouble()); item.passivate(); assertEquals(new Double(22.22), item.getSomeDouble()); assertEquals( list(item), Search.search(item.TYPE, Search.equal(item.someDouble, 22.22))); assertEquals(list(), Search.search(item.TYPE, Search.equal(item.someDouble, null))); assertEquals(list(), Search.search(item.TYPE, Search.isNull(item.someDouble))); item.setSomeDouble(null); assertEquals(null, item.getSomeDouble()); item.passivate(); assertEquals(null, item.getSomeDouble()); } public void testSomeNotNullDouble() { assertEquals(item.TYPE, item.someNotNullDouble.getType()); assertEquals(2.2, item.getSomeNotNullDouble(), 0.0); item.setSomeNotNullDouble(2.5); assertEquals(2.5, item.getSomeNotNullDouble(), 0.0); item.setSomeNotNullDouble(0.0); assertEquals(0.0, item.getSomeNotNullDouble(), 0.0); item.passivate(); assertEquals(0.0, item.getSomeNotNullDouble(), 0.0); assertEquals( set(item), toSet( Search.search( item.TYPE, Search.equal(item.someNotNullDouble, 0.0)))); // TODO: test with extreme values /*item.setSomeNotNullDouble(Double.MIN_VALUE); // TODO: passivate assertEquals(Double.MIN_VALUE, item.getSomeNotNullDouble(), 0.0); assertEquals( set(item), toSet( Search.search( item.TYPE, Search.equal(item.someNotNullDouble, Double.MIN_VALUE)))); item.setSomeNotNullDouble(Double.MAX_VALUE); // TODO: passivate assertEquals(Double.MAX_VALUE, item.getSomeNotNullDouble(), 0.0); assertEquals( set(item), toSet( Search.search( item.TYPE, Search.equal(item.someNotNullDouble, Double.MAX_VALUE))));*/ } public void testSomeBoolean() { assertEquals(item.TYPE, item.someBoolean.getType()); assertEquals(null, item.getSomeBoolean()); item.setSomeBoolean(Boolean.TRUE); assertEquals(Boolean.TRUE, item.getSomeBoolean()); item.setSomeBoolean(Boolean.FALSE); assertEquals(Boolean.FALSE, item.getSomeBoolean()); item.setSomeBoolean(null); assertEquals(null, item.getSomeBoolean()); } public void testSomeNotNullBoolean() { assertEquals(item.TYPE, item.someNotNullBoolean.getType()); assertEquals(true, item.getSomeNotNullBoolean()); item.setSomeNotNullBoolean(false); assertEquals(false, item.getSomeNotNullBoolean()); } public void testSomeItem() { assertEquals(item.TYPE, item.someItem.getType()); assertEquals(ItemWithoutAttributes.TYPE, item.someItem.getTargetType()); assertEquals(null, item.getSomeItem()); item.setSomeItem(someItem); assertEquals(someItem, item.getSomeItem()); item.passivate(); assertEquals(someItem, item.getSomeItem()); item.setSomeItem(null); assertEquals(null, item.getSomeItem()); } public void testSomeNotNullItem() { assertEquals(item.TYPE, item.someNotNullItem.getType()); assertEquals( ItemWithoutAttributes.TYPE, item.someNotNullItem.getTargetType()); assertEquals(someItem, item.getSomeNotNullItem()); try { item.setSomeNotNullItem(someItem2); } catch (NotNullViolationException e) { throw new SystemException(e); } assertEquals(someItem2, item.getSomeNotNullItem()); item.passivate(); assertEquals(someItem2, item.getSomeNotNullItem()); try { item.setSomeNotNullItem(null); fail("should have thrown NotNullViolationException"); } catch (NotNullViolationException e) { assertEquals(item, e.getItem()); assertEquals(item.someNotNullItem, e.getNotNullAttribute()); } assertEquals(someItem2, item.getSomeNotNullItem()); try { someItem2.delete(); } catch(IntegrityViolationException e) { assertEquals(item.someNotNullItem, e.getAttribute()); assertEquals(null/*TODO someItem*/, e.getItem()); } try { new ItemWithManyAttributes("someString", 5, 2.2, true, null, ItemWithManyAttributes.SomeEnumeration.enumValue1); fail("should have thrown NotNullViolationException"); } catch(NotNullViolationException e) { assertEquals(null, e.getItem()); assertEquals(item.someNotNullItem, e.getNotNullAttribute()); } } public void testSomeEnumeration() { assertEquals(null, item.getSomeEnumeration()); item.setSomeEnumeration(ItemWithManyAttributes.SomeEnumeration.enumValue1); assertEquals( ItemWithManyAttributes.SomeEnumeration.enumValue1, item.getSomeEnumeration()); item.setSomeEnumeration( ItemWithManyAttributes.SomeEnumeration.enumValue2); assertEquals( ItemWithManyAttributes.SomeEnumeration.enumValue2, item.getSomeEnumeration()); item.passivate(); assertEquals( ItemWithManyAttributes.SomeEnumeration.enumValue2, item.getSomeEnumeration()); item.setSomeEnumeration(null); assertEquals(null, item.getSomeEnumeration()); } public void testNotNullSomeEnumeration() throws NotNullViolationException { assertEquals(ItemWithManyAttributes.SomeEnumeration.enumValue1, item.getSomeNotNullEnumeration()); item.setSomeNotNullEnumeration(ItemWithManyAttributes.SomeEnumeration.enumValue2); assertEquals( ItemWithManyAttributes.SomeEnumeration.enumValue2, item.getSomeNotNullEnumeration()); item.setSomeNotNullEnumeration( ItemWithManyAttributes.SomeEnumeration.enumValue3); assertEquals( ItemWithManyAttributes.SomeEnumeration.enumValue3, item.getSomeNotNullEnumeration()); item.passivate(); assertEquals( ItemWithManyAttributes.SomeEnumeration.enumValue3, item.getSomeNotNullEnumeration()); try { item.setSomeNotNullEnumeration(null); } catch(NotNullViolationException e) { assertEquals(item, e.getItem()); assertEquals(item.someNotNullEnumeration, e.getNotNullAttribute()); } assertEquals( ItemWithManyAttributes.SomeEnumeration.enumValue3, item.getSomeNotNullEnumeration()); try { new ItemWithManyAttributes("someString", 5, 2.2, true, someItem, null); fail("should have thrown NotNullViolationException"); } catch(NotNullViolationException e) { assertEquals(null, e.getItem()); assertEquals(item.someNotNullEnumeration, e.getNotNullAttribute()); } } public void testSomeMedia() throws IOException { // TODO: dotestItemWithManyAttributesSomeNotNullMedia(item); assertEquals(item.TYPE, item.someMedia.getType()); assertEquals(null, item.getSomeMediaURL()); assertEquals(null, item.getSomeMediaURLSomeVariant()); assertEquals(null, item.getSomeMediaData()); assertEquals(null, item.getSomeMediaMimeMajor()); assertEquals(null, item.getSomeMediaMimeMinor()); final byte[] bytes = new byte[]{3,7,1,4}; item.setSomeMediaData(new ByteArrayInputStream(bytes),"someMimeMajor", "someMimeMinor"); final String prefix = "/medias/ItemWithManyAttributes/someMedia/"; final String pkString = String.valueOf(Search.pk2id(item.pk)); final String expectedURL = prefix + pkString + ".someMimeMajor.someMimeMinor"; final String expectedURLSomeVariant = prefix + "SomeVariant/" + pkString + ".someMimeMajor.someMimeMinor"; //System.out.println(expectedURL); //System.out.println(item.getSomeMediaURL()); assertEquals(expectedURL, item.getSomeMediaURL()); assertEquals(expectedURLSomeVariant, item.getSomeMediaURLSomeVariant()); assertData(bytes, item.getSomeMediaData()); assertEquals("someMimeMajor", item.getSomeMediaMimeMajor()); assertEquals("someMimeMinor", item.getSomeMediaMimeMinor()); item.passivate(); assertEquals(expectedURL, item.getSomeMediaURL()); assertEquals(expectedURLSomeVariant, item.getSomeMediaURLSomeVariant()); assertData(bytes, item.getSomeMediaData()); assertEquals("someMimeMajor", item.getSomeMediaMimeMajor()); assertEquals("someMimeMinor", item.getSomeMediaMimeMinor()); assertMediaMime(item, "image", "jpeg", bytes, "jpg"); assertMediaMime(item, "image", "pjpeg", bytes, "jpg"); assertMediaMime(item, "image", "gif", bytes, "gif"); assertMediaMime(item, "image", "png", bytes, "png"); assertMediaMime(item, "image", "someMinor", bytes, "image.someMinor"); item.setSomeMediaData(null, null, null); assertEquals(null, item.getSomeMediaURL()); assertEquals(null, item.getSomeMediaURLSomeVariant()); assertEquals(null, item.getSomeMediaData()); assertEquals(null, item.getSomeMediaMimeMajor()); assertEquals(null, item.getSomeMediaMimeMinor()); } public void testSomeQualifiedAttribute() throws IntegrityViolationException { assertEquals(item.TYPE, item.someQualifiedString.getType()); final ItemWithoutAttributes someItem2 = new ItemWithoutAttributes(); assertEquals(null, item.getSomeQualifiedString(someItem)); assertEquals(null, item.getSomeQualifiedString(someItem2)); item.setSomeQualifiedString(someItem, "someQualifiedValue"); assertEquals("someQualifiedValue", item.getSomeQualifiedString(someItem)); assertEquals("someQualifiedValue" /*null TODO*/, item.getSomeQualifiedString(someItem2)); item.passivate(); assertEquals("someQualifiedValue", item.getSomeQualifiedString(someItem)); assertEquals("someQualifiedValue" /*null TODO*/, item.getSomeQualifiedString(someItem2)); item.setSomeQualifiedString(someItem, null); assertEquals(null, item.getSomeQualifiedString(someItem)); assertEquals(null, item.getSomeQualifiedString(someItem2)); assertDelete(someItem2); } }
package picocli.shell.jline3; import org.jline.builtins.Completers.OptionCompleter; import org.jline.builtins.Completers.SystemCompleter; import org.jline.builtins.Options.HelpException; import org.jline.builtins.Widgets.ArgDesc; import org.jline.builtins.Widgets.CmdDesc; import org.jline.reader.Completer; import org.jline.reader.impl.completer.AggregateCompleter; import org.jline.reader.impl.completer.ArgumentCompleter; import org.jline.reader.impl.completer.NullCompleter; import org.jline.reader.impl.completer.StringsCompleter; import org.jline.utils.AttributedString; import picocli.CommandLine; import picocli.CommandLine.Help; import picocli.CommandLine.Model.CommandSpec; import picocli.CommandLine.Model.OptionSpec; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Supplier; import java.util.stream.Collectors; /** * Compiles SystemCompleter for command completion and implements a method commandDescription() that provides command descriptions * for JLine TailTipWidgets to be displayed in terminal status bar. * SystemCompleter implements the JLine 3 {@link Completer} interface. SystemCompleter generates completion * candidates for the specified command line based on the {@link CommandSpec} that this {@code PicocliCommands} was constructed with. * * @since 4.1.2 */ public class PicocliCommands { private final Supplier<Path> workDir; private final CommandLine cmd; private final List<String> commands; private final Map<String, String> aliasCommand; public PicocliCommands(Path workDir, CommandLine cmd) { this(() -> workDir, cmd); } public PicocliCommands(Supplier<Path> workDir, CommandLine cmd) { this.workDir = workDir; this.cmd = cmd; commands = new ArrayList<>(cmd.getCommandSpec().subcommands().keySet()); aliasCommand = extractAliases(cmd); } private static Map<String, String> extractAliases(CommandLine cmd) { Map<String, String> result = new LinkedHashMap<>(); for (String name : cmd.getCommandSpec().subcommands().keySet()) { for (String alias : cmd.getSubcommands().get(name).getCommandSpec().aliases()) { result.put(alias, name); } } return result; } /** * * @param command * @return true if PicocliCommands contains command */ public boolean hasCommand(String command) { return commands.contains(command) || aliasCommand.containsKey(command); } private static class CommandHierarchyCompleter extends SystemCompleter { List<CommandHierarchyCompleter> nested = new ArrayList<>(); @Override public void compile() { super.compile(); nested.forEach(CommandHierarchyCompleter::compile); } } /** * * @return SystemCompleter for command completion */ public SystemCompleter compileCompleters() { return createCompilableCompleter(cmd); } private CommandHierarchyCompleter createCompilableCompleter(CommandLine cmd) { CommandHierarchyCompleter result = new CommandHierarchyCompleter(); for (CommandLine sub : cmd.getSubcommands().values()) { String commandName = sub.getCommandName(); for (String alias : sub.getCommandSpec().aliases()) { result.getAliases().put(alias, commandName); } ArgumentCompleter argumentCompleter = createArgumentCompleter(result, sub.getCommandSpec()); result.add(commandName, argumentCompleter); } return result; } private ArgumentCompleter createArgumentCompleter(CommandHierarchyCompleter hierarchy, CommandSpec spec) { Completer optionCompleter = createOptionCompleter(hierarchy, spec); return new ArgumentCompleter(new StringsCompleter(spec.name()), optionCompleter); } private Completer createOptionCompleter(CommandHierarchyCompleter hierarchy, CommandSpec spec) { // TODO positional parameter completion // JLine OptionCompleter need to be improved with option descriptions and option value completion, // now it completes only strings. List<String> options = new ArrayList<>(); Map<String, List<String>> optionValues = new HashMap<>(); for (OptionSpec option : spec.options()) { if (option.arity().max() == 0) { options.addAll(Arrays.asList(option.names())); } else { List<String> values = new ArrayList<>(); if (option.completionCandidates() != null) { option.completionCandidates().forEach(values::add); } for (String name : option.names()) { optionValues.put(name, values); } } } List<Completer> subcommands = new ArrayList<>(); // for (CommandLine sub : spec.subcommands().values()) { // // TODO unfortunately createCompilableCompleter will not include an OptionCompleter for sub... // CommandHierarchyCompleter subCompleter = createCompilableCompleter(sub); // hierarchy.nested.add(subCompleter); // ensure subCompleter is compiled when top-level completer is compiled // subcommands.add(subCompleter); // Completer nestedCompleters = new AggregateCompleter(subcommands); Completer nestedCompleters = NullCompleter.INSTANCE; return options.isEmpty() && optionValues.isEmpty() && subcommands.isEmpty() ? NullCompleter.INSTANCE : new OptionCompleter(nestedCompleters, optionValues, options, 1); } /** * * @param command * @return command description for JLine TailTipWidgets to be displayed in terminal status bar. */ public CmdDesc commandDescription(String command) { CommandSpec spec = cmd.getSubcommands().get(command).getCommandSpec(); Help cmdhelp= new picocli.CommandLine.Help(spec); List<AttributedString> main = new ArrayList<>(); Map<String, List<AttributedString>> options = new HashMap<>(); String synopsis = AttributedString.stripAnsi(spec.usageMessage().sectionMap().get("synopsis").render(cmdhelp).toString()); main.add(HelpException.highlightSyntax(synopsis.trim(), HelpException.defaultStyle())); // using JLine help highlight because the statement below does not work well... // main.add(new AttributedString(spec.usageMessage().sectionMap().get("synopsis").render(cmdhelp).toString())); for (OptionSpec o : spec.options()) { String key = Arrays.stream(o.names()).collect(Collectors.joining(" ")); List<AttributedString> val = new ArrayList<>(); for (String d: o.description()) { val.add(new AttributedString(d)); } if (val.isEmpty()) { val.add(new AttributedString("")); // in order to avoid IndexOutOfBoundsException // need to be fixed in JLine } if (o.arity().max() > 0 && key.matches(".*[a-zA-Z]{2,}$")) { key += "=" + o.paramLabel(); } options.put(key, val); } return new CmdDesc(main, ArgDesc.doArgNames(Arrays.asList("")), options); } }
package org.bouncycastle.operator; import java.util.HashMap; import java.util.Map; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.bsi.BSIObjectIdentifiers; import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; import org.bouncycastle.asn1.eac.EACObjectIdentifiers; import org.bouncycastle.asn1.gnu.GNUObjectIdentifiers; import org.bouncycastle.asn1.kisa.KISAObjectIdentifiers; import org.bouncycastle.asn1.misc.MiscObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.ntt.NTTObjectIdentifiers; import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.rosstandart.RosstandartObjectIdentifiers; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; public class DefaultAlgorithmNameFinder implements AlgorithmNameFinder { private final static Map algorithms = new HashMap(); static { algorithms.put(BSIObjectIdentifiers.ecdsa_plain_RIPEMD160, "RIPEMD160WITHPLAIN-ECDSA"); algorithms.put(BSIObjectIdentifiers.ecdsa_plain_SHA1, "SHA1WITHPLAIN-ECDSA"); algorithms.put(BSIObjectIdentifiers.ecdsa_plain_SHA224, "SHA224WITHPLAIN-ECDSA"); algorithms.put(BSIObjectIdentifiers.ecdsa_plain_SHA256, "SHA256WITHPLAIN-ECDSA"); algorithms.put(BSIObjectIdentifiers.ecdsa_plain_SHA384, "SHA384WITHPLAIN-ECDSA"); algorithms.put(BSIObjectIdentifiers.ecdsa_plain_SHA512, "SHA512WITHPLAIN-ECDSA"); algorithms.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001, "GOST3411WITHECGOST3410-2001"); algorithms.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94, "GOST3411WITHGOST3410-94"); algorithms.put(CryptoProObjectIdentifiers.gostR3411, "GOST3411"); algorithms.put(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256, "GOST3411WITHECGOST3410-2012-256"); algorithms.put(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512, "GOST3411WITHECGOST3410-2012-512"); algorithms.put(EACObjectIdentifiers.id_TA_ECDSA_SHA_1, "SHA1WITHCVC-ECDSA"); algorithms.put(EACObjectIdentifiers.id_TA_ECDSA_SHA_224, "SHA224WITHCVC-ECDSA"); algorithms.put(EACObjectIdentifiers.id_TA_ECDSA_SHA_256, "SHA256WITHCVC-ECDSA"); algorithms.put(EACObjectIdentifiers.id_TA_ECDSA_SHA_384, "SHA384WITHCVC-ECDSA"); algorithms.put(EACObjectIdentifiers.id_TA_ECDSA_SHA_512, "SHA512WITHCVC-ECDSA"); algorithms.put(NISTObjectIdentifiers.id_sha224, "SHA224"); algorithms.put(NISTObjectIdentifiers.id_sha256, "SHA256"); algorithms.put(NISTObjectIdentifiers.id_sha384, "SHA384"); algorithms.put(NISTObjectIdentifiers.id_sha512, "SHA512"); algorithms.put(NISTObjectIdentifiers.id_sha3_224, "SHA3-224"); algorithms.put(NISTObjectIdentifiers.id_sha3_256, "SHA3-256"); algorithms.put(NISTObjectIdentifiers.id_sha3_384, "SHA3-384"); algorithms.put(NISTObjectIdentifiers.id_sha3_512, "SHA3-512"); algorithms.put(OIWObjectIdentifiers.elGamalAlgorithm, "ELGAMAL"); algorithms.put(OIWObjectIdentifiers.idSHA1, "SHA1"); algorithms.put(OIWObjectIdentifiers.md5WithRSA, "MD5WITHRSA"); algorithms.put(OIWObjectIdentifiers.sha1WithRSA, "SHA1WITHRSA"); algorithms.put(PKCSObjectIdentifiers.id_RSAES_OAEP, "RSAOAEP"); algorithms.put(PKCSObjectIdentifiers.id_RSASSA_PSS, "RSAPSS"); algorithms.put(PKCSObjectIdentifiers.md2WithRSAEncryption, "MD2WITHRSA"); algorithms.put(PKCSObjectIdentifiers.md5, "MD5"); algorithms.put(PKCSObjectIdentifiers.md5WithRSAEncryption, "MD5WITHRSA"); algorithms.put(PKCSObjectIdentifiers.rsaEncryption, "RSA"); algorithms.put(PKCSObjectIdentifiers.sha1WithRSAEncryption, "SHA1WITHRSA"); algorithms.put(PKCSObjectIdentifiers.sha224WithRSAEncryption, "SHA224WITHRSA"); algorithms.put(PKCSObjectIdentifiers.sha256WithRSAEncryption, "SHA256WITHRSA"); algorithms.put(PKCSObjectIdentifiers.sha384WithRSAEncryption, "SHA384WITHRSA"); algorithms.put(PKCSObjectIdentifiers.sha512WithRSAEncryption, "SHA512WITHRSA"); algorithms.put(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_224, "SHA3-224WITHRSA"); algorithms.put(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_256, "SHA3-256WITHRSA"); algorithms.put(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_384, "SHA3-384WITHRSA"); algorithms.put(NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_512, "SHA3-512WITHRSA"); algorithms.put(TeleTrusTObjectIdentifiers.ripemd128, "RIPEMD128"); algorithms.put(TeleTrusTObjectIdentifiers.ripemd160, "RIPEMD160"); algorithms.put(TeleTrusTObjectIdentifiers.ripemd256, "RIPEMD256"); algorithms.put(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128, "RIPEMD128WITHRSA"); algorithms.put(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160, "RIPEMD160WITHRSA"); algorithms.put(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256, "RIPEMD256WITHRSA"); algorithms.put(X9ObjectIdentifiers.ecdsa_with_SHA1, "ECDSAWITHSHA1"); algorithms.put(X9ObjectIdentifiers.ecdsa_with_SHA224, "SHA224WITHECDSA"); algorithms.put(X9ObjectIdentifiers.ecdsa_with_SHA256, "SHA256WITHECDSA"); algorithms.put(X9ObjectIdentifiers.ecdsa_with_SHA384, "SHA384WITHECDSA"); algorithms.put(X9ObjectIdentifiers.ecdsa_with_SHA512, "SHA512WITHECDSA"); algorithms.put(NISTObjectIdentifiers.id_ecdsa_with_sha3_224, "SHA3-224WITHECDSA"); algorithms.put(NISTObjectIdentifiers.id_ecdsa_with_sha3_256, "SHA3-256WITHECDSA"); algorithms.put(NISTObjectIdentifiers.id_ecdsa_with_sha3_384, "SHA3-384WITHECDSA"); algorithms.put(NISTObjectIdentifiers.id_ecdsa_with_sha3_512, "SHA3-512WITHECDSA"); algorithms.put(X9ObjectIdentifiers.id_dsa_with_sha1, "SHA1WITHDSA"); algorithms.put(NISTObjectIdentifiers.dsa_with_sha224, "SHA224WITHDSA"); algorithms.put(NISTObjectIdentifiers.dsa_with_sha256, "SHA256WITHDSA"); algorithms.put(NISTObjectIdentifiers.dsa_with_sha384, "SHA384WITHDSA"); algorithms.put(NISTObjectIdentifiers.dsa_with_sha512, "SHA512WITHDSA"); algorithms.put(NISTObjectIdentifiers.id_dsa_with_sha3_224, "SHA3-224WITHDSA"); algorithms.put(NISTObjectIdentifiers.id_dsa_with_sha3_256, "SHA3-256WITHDSA"); algorithms.put(NISTObjectIdentifiers.id_dsa_with_sha3_384, "SHA3-384WITHDSA"); algorithms.put(NISTObjectIdentifiers.id_dsa_with_sha3_512, "SHA3-512WITHDSA"); algorithms.put(GNUObjectIdentifiers.Tiger_192, "Tiger"); algorithms.put(PKCSObjectIdentifiers.RC2_CBC, "RC2/CBC"); algorithms.put(PKCSObjectIdentifiers.des_EDE3_CBC, "DESEDE-3KEY/CBC"); algorithms.put(NISTObjectIdentifiers.id_aes128_ECB, "AES-128/ECB"); algorithms.put(NISTObjectIdentifiers.id_aes192_ECB, "AES-192/ECB"); algorithms.put(NISTObjectIdentifiers.id_aes256_ECB, "AES-256/ECB"); algorithms.put(NISTObjectIdentifiers.id_aes128_CBC, "AES-128/CBC"); algorithms.put(NISTObjectIdentifiers.id_aes192_CBC, "AES-192/CBC"); algorithms.put(NISTObjectIdentifiers.id_aes256_CBC, "AES-256/CBC"); algorithms.put(NISTObjectIdentifiers.id_aes128_CFB, "AES-128/CFB"); algorithms.put(NISTObjectIdentifiers.id_aes192_CFB, "AES-192/CFB"); algorithms.put(NISTObjectIdentifiers.id_aes256_CFB, "AES-256/CFB"); algorithms.put(NISTObjectIdentifiers.id_aes128_OFB, "AES-128/OFB"); algorithms.put(NISTObjectIdentifiers.id_aes192_OFB, "AES-192/OFB"); algorithms.put(NISTObjectIdentifiers.id_aes256_OFB, "AES-256/OFB"); algorithms.put(NTTObjectIdentifiers.id_camellia128_cbc, "CAMELLIA-128/CBC"); algorithms.put(NTTObjectIdentifiers.id_camellia192_cbc, "CAMELLIA-192/CBC"); algorithms.put(NTTObjectIdentifiers.id_camellia256_cbc, "CAMELLIA-256/CBC"); algorithms.put(KISAObjectIdentifiers.id_seedCBC, "SEED/CBC"); algorithms.put(MiscObjectIdentifiers.as_sys_sec_alg_ideaCBC, "IDEA/CBC"); algorithms.put(MiscObjectIdentifiers.cast5CBC, "CAST5/CBC"); algorithms.put(MiscObjectIdentifiers.cryptlib_algorithm_blowfish_ECB, "Blowfish/ECB"); algorithms.put(MiscObjectIdentifiers.cryptlib_algorithm_blowfish_CBC, "Blowfish/CBC"); algorithms.put(MiscObjectIdentifiers.cryptlib_algorithm_blowfish_CFB, "Blowfish/CFB"); algorithms.put(MiscObjectIdentifiers.cryptlib_algorithm_blowfish_OFB, "Blowfish/OFB"); algorithms.put(GNUObjectIdentifiers.Serpent_128_ECB, "Serpent-128/ECB"); algorithms.put(GNUObjectIdentifiers.Serpent_128_CBC, "Serpent-128/CBC"); algorithms.put(GNUObjectIdentifiers.Serpent_128_CFB, "Serpent-128/CFB"); algorithms.put(GNUObjectIdentifiers.Serpent_128_OFB, "Serpent-128/OFB"); algorithms.put(GNUObjectIdentifiers.Serpent_192_ECB, "Serpent-192/ECB"); algorithms.put(GNUObjectIdentifiers.Serpent_192_CBC, "Serpent-192/CBC"); algorithms.put(GNUObjectIdentifiers.Serpent_192_CFB, "Serpent-192/CFB"); algorithms.put(GNUObjectIdentifiers.Serpent_192_OFB, "Serpent-192/OFB"); algorithms.put(GNUObjectIdentifiers.Serpent_256_ECB, "Serpent-256/ECB"); algorithms.put(GNUObjectIdentifiers.Serpent_256_CBC, "Serpent-256/CBC"); algorithms.put(GNUObjectIdentifiers.Serpent_256_CFB, "Serpent-256/CFB"); algorithms.put(GNUObjectIdentifiers.Serpent_256_OFB, "Serpent-256/OFB"); } public boolean hasAlgorithmName(ASN1ObjectIdentifier objectIdentifier) { return algorithms.containsKey(objectIdentifier); } public String getAlgorithmName(ASN1ObjectIdentifier objectIdentifier) { String name = (String)algorithms.get(objectIdentifier); return (name != null) ? name : objectIdentifier.getId(); } public String getAlgorithmName(AlgorithmIdentifier algorithmIdentifier) { // TODO: take into account PSS/OAEP params return getAlgorithmName(algorithmIdentifier.getAlgorithm()); } }
package com.intellij.usages.impl; import com.intellij.diagnostic.PerformanceWatcher; import com.intellij.find.FindManager; import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.KeyboardShortcut; import com.intellij.openapi.application.AppUIExecutor; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.colors.CodeInsightColors; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.module.UnloadedModuleDescription; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.impl.CoreProgressManager; import com.intellij.openapi.progress.util.ProgressWrapper; import com.intellij.openapi.progress.util.TooManyUsagesStatus; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Factory; import com.intellij.openapi.util.Segment; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.ToolWindowId; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.psi.PsiElement; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.SearchScope; import com.intellij.ui.HyperlinkAdapter; import com.intellij.usageView.UsageViewBundle; import com.intellij.usageView.UsageViewContentManager; import com.intellij.usages.*; import com.intellij.util.Alarm; import com.intellij.util.Processor; import com.intellij.util.Processors; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.RangeBlinker; import com.intellij.xml.util.XmlStringUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; final class SearchForUsagesRunnable implements Runnable { @NonNls private static final String FIND_OPTIONS_HREF_TARGET = "FindOptions"; @NonNls private static final String SEARCH_IN_PROJECT_HREF_TARGET = "SearchInProject"; @NonNls private static final String LARGE_FILES_HREF_TARGET = "LargeFiles"; @NonNls private static final String SHOW_PROJECT_FILE_OCCURRENCES_HREF_TARGET = "SHOW_PROJECT_FILE_OCCURRENCES"; private final AtomicInteger myUsageCountWithoutDefinition = new AtomicInteger(0); private final AtomicReference<Usage> myFirstUsage = new AtomicReference<>(); @NotNull private final Project myProject; private final AtomicReference<UsageViewEx> myUsageViewRef; private final UsageViewPresentation myPresentation; private final UsageTarget[] mySearchFor; private final Factory<UsageSearcher> mySearcherFactory; private final FindUsagesProcessPresentation myProcessPresentation; @NotNull private final SearchScope mySearchScopeToWarnOfFallingOutOf; private final UsageViewManager.UsageViewStateListener myListener; private final UsageViewManagerImpl myUsageViewManager; private final AtomicInteger myOutOfScopeUsages = new AtomicInteger(); SearchForUsagesRunnable(@NotNull UsageViewManagerImpl usageViewManager, @NotNull Project project, @NotNull AtomicReference<UsageViewEx> usageViewRef, @NotNull UsageViewPresentation presentation, UsageTarget @NotNull [] searchFor, @NotNull Factory<UsageSearcher> searcherFactory, @NotNull FindUsagesProcessPresentation processPresentation, @NotNull SearchScope searchScopeToWarnOfFallingOutOf, @Nullable UsageViewManager.UsageViewStateListener listener) { myProject = project; myUsageViewRef = usageViewRef; myPresentation = presentation; mySearchFor = searchFor; mySearcherFactory = searcherFactory; myProcessPresentation = processPresentation; mySearchScopeToWarnOfFallingOutOf = searchScopeToWarnOfFallingOutOf; myListener = listener; myUsageViewManager = usageViewManager; } @NotNull private static String createOptionsHtml(@NonNls UsageTarget @NotNull [] searchFor) { KeyboardShortcut shortcut = UsageViewImpl.getShowUsagesWithSettingsShortcut(searchFor); String shortcutText = ""; if (shortcut != null) { shortcutText = "&nbsp;(" + KeymapUtil.getShortcutText(shortcut) + ")"; } return "<a href='" + FIND_OPTIONS_HREF_TARGET + "'>Find Options...</a>" + shortcutText; } @NotNull private static String createSearchInProjectHtml() { return "<a href='" + SEARCH_IN_PROJECT_HREF_TARGET + "'>Search in Project</a>"; } private void notifyByFindBalloon(@Nullable final HyperlinkListener listener, @NotNull final MessageType messageType, @NotNull final List<String> lines) { UsageViewContentManager.getInstance(myProject); // in case tool window not registered final Collection<VirtualFile> largeFiles = myProcessPresentation.getLargeFiles(); List<String> resultLines = new ArrayList<>(lines); HyperlinkListener resultListener = listener; if (!largeFiles.isEmpty()) { String shortMessage = "(<a href='" + LARGE_FILES_HREF_TARGET + "'>" + UsageViewBundle.message("large.files.were.ignored", largeFiles.size()) + "</a>)"; resultLines.add(shortMessage); resultListener = addHrefHandling(resultListener, LARGE_FILES_HREF_TARGET, () -> { String detailedMessage = detailedLargeFilesMessage(largeFiles); List<String> strings = new ArrayList<>(lines); strings.add(detailedMessage); //noinspection SSBasedInspection ToolWindowManager.getInstance(myProject).notifyByBalloon(ToolWindowId.FIND, messageType, wrapInHtml(strings), AllIcons.Actions.Find, listener); }); } Runnable searchIncludingProjectFileUsages = myProcessPresentation.searchIncludingProjectFileUsages(); if (searchIncludingProjectFileUsages != null) { resultLines.add("Occurrences in project configuration files are skipped. " + "<a href='" + SHOW_PROJECT_FILE_OCCURRENCES_HREF_TARGET + "'>Include them</a>"); resultListener = addHrefHandling(resultListener, SHOW_PROJECT_FILE_OCCURRENCES_HREF_TARGET, searchIncludingProjectFileUsages); } Collection<UnloadedModuleDescription> unloaded = getUnloadedModulesBelongingToScope(); MessageType actualType = messageType; if (!unloaded.isEmpty()) { if (actualType == MessageType.INFO) { actualType = MessageType.WARNING; } resultLines.add(mayHaveUsagesInUnloadedModulesMessage(unloaded)); } //noinspection SSBasedInspection ToolWindowManager.getInstance(myProject).notifyByBalloon(ToolWindowId.FIND, actualType, wrapInHtml(resultLines), AllIcons.Actions.Find, resultListener); } @NotNull private Collection<UnloadedModuleDescription> getUnloadedModulesBelongingToScope() { return ReadAction.compute(() -> { if (!(mySearchScopeToWarnOfFallingOutOf instanceof GlobalSearchScope)) return Collections.emptySet(); Collection<UnloadedModuleDescription> unloadedInSearchScope = ((GlobalSearchScope)mySearchScopeToWarnOfFallingOutOf).getUnloadedModulesBelongingToScope(); Set<UnloadedModuleDescription> unloadedInUseScope = getUnloadedModulesBelongingToUseScopes(); if (unloadedInUseScope != null) { //when searching for usages of PsiElements return only those unloaded modules which may contain references to the elements, this way // we won't show a warning if e.g. 'find usages' for a private method is invoked return ContainerUtil.intersection(unloadedInSearchScope, unloadedInUseScope); } return unloadedInSearchScope; }); } private Set<UnloadedModuleDescription> getUnloadedModulesBelongingToUseScopes() { Set<UnloadedModuleDescription> resolveScope = new LinkedHashSet<>(); for (UsageTarget target : mySearchFor) { if (!(target instanceof PsiElementUsageTarget)) return null; PsiElement element = ((PsiElementUsageTarget)target).getElement(); if (element == null) return null; SearchScope useScope = element.getUseScope(); if (useScope instanceof GlobalSearchScope) { resolveScope.addAll(((GlobalSearchScope)useScope).getUnloadedModulesBelongingToScope()); } } return resolveScope; } @NotNull private static HyperlinkListener addHrefHandling(@Nullable final HyperlinkListener listener, @NotNull final String hrefTarget, @NotNull final Runnable handler) { return new HyperlinkAdapter() { @Override protected void hyperlinkActivated(HyperlinkEvent e) { if (e.getDescription().equals(hrefTarget)) { handler.run(); } else if (listener != null) { listener.hyperlinkUpdate(e); } } }; } @NotNull private static String wrapInHtml(@NotNull List<String> strings) { return XmlStringUtil.wrapInHtml(StringUtil.join(strings, "<br>")); } @NotNull private static String detailedLargeFilesMessage(@NotNull Collection<? extends VirtualFile> largeFiles) { String message; if (largeFiles.size() == 1) { final VirtualFile vFile = largeFiles.iterator().next(); message = "File " + presentableFileInfo(vFile) + " is "; } else { message = "Files<br> " + StringUtil.join(ContainerUtil.getFirstItems(new ArrayList<>(largeFiles), 10), vFile -> presentableFileInfo(vFile), "<br> ") + "<br> are "; } message += "too large and cannot be scanned"; return message; } @NotNull private static String presentableFileInfo(@NotNull VirtualFile vFile) { return getPresentablePath(vFile) + "&nbsp;(" + UsageViewManagerImpl.presentableSize(UsageViewManagerImpl.getFileLength(vFile)) + ")"; } @NotNull private static String getPresentablePath(@NotNull final VirtualFile virtualFile) { return "'" + ReadAction.compute(virtualFile::getPresentableUrl) + "'"; } @NotNull private HyperlinkListener createGotToOptionsListener(final UsageTarget @NotNull [] targets) { return new HyperlinkAdapter() { @Override protected void hyperlinkActivated(HyperlinkEvent e) { if (e.getDescription().equals(FIND_OPTIONS_HREF_TARGET)) { FindManager.getInstance(myProject).showSettingsAndFindUsages(targets); } } }; } @NotNull private HyperlinkListener createSearchInProjectListener() { return new HyperlinkAdapter() { @Override protected void hyperlinkActivated(HyperlinkEvent e) { if (e.getDescription().equals(SEARCH_IN_PROJECT_HREF_TARGET)) { PsiElement psiElement = getPsiElement(mySearchFor); if (psiElement != null) { FindManager.getInstance(myProject).findUsagesInScope(psiElement, GlobalSearchScope.projectScope(myProject)); } } } }; } private static PsiElement getPsiElement(UsageTarget @NotNull [] searchFor) { final UsageTarget target = searchFor[0]; if (!(target instanceof PsiElementUsageTarget)) return null; return ReadAction.compute(((PsiElementUsageTarget)target)::getElement); } private static void flashUsageScriptaculously(@NotNull final Usage usage) { if (!(usage instanceof UsageInfo2UsageAdapter)) { return; } UsageInfo2UsageAdapter usageInfo = (UsageInfo2UsageAdapter)usage; Editor editor = usageInfo.openTextEditor(true); if (editor == null) return; TextAttributes attributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(CodeInsightColors.BLINKING_HIGHLIGHTS_ATTRIBUTES); RangeBlinker rangeBlinker = new RangeBlinker(editor, attributes, 6); List<Segment> segments = new ArrayList<>(); Processor<Segment> processor = Processors.cancelableCollectProcessor(segments); usageInfo.processRangeMarkers(processor); rangeBlinker.resetMarkers(segments); rangeBlinker.startBlinking(); } private UsageViewEx getUsageView(@NotNull ProgressIndicator indicator, long startSearchStamp) { UsageViewEx usageView = myUsageViewRef.get(); if (usageView != null) { return usageView; } int usageCount = myUsageCountWithoutDefinition.get(); if (usageCount == 0 || usageCount == 1 && !myProcessPresentation.isShowPanelIfOnlyOneUsage() && System.currentTimeMillis() < startSearchStamp + 500) { return null; } usageView = myUsageViewManager.createUsageView(mySearchFor, Usage.EMPTY_ARRAY, myPresentation, mySearcherFactory); if (myUsageViewRef.compareAndSet(null, usageView)) { // associate progress only if created successfully, otherwise Dispose will cancel the actual progress, see IDEA-195542 usageView.associateProgress(indicator); if (myProcessPresentation.isShowFindOptionsPrompt()) { openView(usageView); } else if (myListener != null) { SwingUtilities.invokeLater(() -> { if (!myProject.isDisposed()) { UsageViewEx uv = myUsageViewRef.get(); if (uv != null) { myListener.usageViewCreated(uv); } } }); } Usage firstUsage = myFirstUsage.get(); if (firstUsage != null) { UsageViewEx finalUsageView = usageView; ApplicationManager.getApplication().runReadAction(() -> finalUsageView.appendUsage(firstUsage)); } } else { UsageViewEx finalUsageView = usageView; Disposer.register(myProject, usageView); // UI thread because dispose does some sort of swing magic e.g. AnAction.unregisterCustomShortcutSet() AppUIExecutor.onUiThread(ModalityState.any()).expireWith(myProject).execute(() -> Disposer.dispose(finalUsageView)); } return myUsageViewRef.get(); } private void openView(@NotNull final UsageViewEx usageView) { SwingUtilities.invokeLater(() -> { if (myProject.isDisposed()) return; myUsageViewManager.showUsageView(usageView, myPresentation); if (myListener != null) { myListener.usageViewCreated(usageView); } myUsageViewManager.showToolWindow(false); }); } @Override public void run() { PerformanceWatcher.Snapshot snapshot = PerformanceWatcher.takeSnapshot(); AtomicBoolean findUsagesStartedShown = new AtomicBoolean(); searchUsages(findUsagesStartedShown); endSearchForUsages(findUsagesStartedShown); snapshot.logResponsivenessSinceCreation("Find Usages"); } private void searchUsages(@NotNull final AtomicBoolean findStartedBalloonShown) { ProgressIndicator current = ProgressManager.getInstance().getProgressIndicator(); if (current == null) throw new IllegalStateException("must run find usages under progress"); ProgressIndicator indicator = ProgressWrapper.unwrapAll(current); if (!ApplicationManager.getApplication().isDispatchThread()) { CoreProgressManager.assertUnderProgress(indicator); } TooManyUsagesStatus.createFor(indicator); Alarm findUsagesStartedBalloon = new Alarm(); findUsagesStartedBalloon.addRequest(() -> { notifyByFindBalloon(null, MessageType.WARNING, Collections.singletonList(StringUtil.escapeXmlEntities(UsageViewManagerImpl.getProgressTitle(myPresentation)))); findStartedBalloonShown.set(true); }, 300, ModalityState.NON_MODAL); UsageSearcher usageSearcher = mySearcherFactory.create(); long startSearchStamp = System.currentTimeMillis(); usageSearcher.generate(usage -> { ProgressIndicator currentIndicator = ProgressManager.getInstance().getProgressIndicator(); if (currentIndicator == null) throw new IllegalStateException("must run find usages under progress"); ProgressIndicator originalIndicator = ProgressWrapper.unwrapAll(current); ProgressManager.checkCanceled(); if (!UsageViewManagerImpl.isInScope(usage, mySearchScopeToWarnOfFallingOutOf)) { myOutOfScopeUsages.incrementAndGet(); return true; } boolean incrementCounter = !UsageViewManager.isSelfUsage(usage, mySearchFor); if (incrementCounter) { final int usageCount = myUsageCountWithoutDefinition.incrementAndGet(); if (usageCount == 1 && !myProcessPresentation.isShowPanelIfOnlyOneUsage()) { myFirstUsage.compareAndSet(null, usage); } UsageViewEx usageView = getUsageView(originalIndicator, startSearchStamp); TooManyUsagesStatus tooManyUsagesStatus= TooManyUsagesStatus.getFrom(originalIndicator); if (usageCount > UsageLimitUtil.USAGES_LIMIT && tooManyUsagesStatus.switchTooManyUsagesStatus()) { UsageViewManagerImpl.showTooManyUsagesWarningLater(myProject, tooManyUsagesStatus, originalIndicator, myPresentation, usageCount, usageView); } tooManyUsagesStatus.pauseProcessingIfTooManyUsages(); if (usageView != null) { ApplicationManager.getApplication().runReadAction(() -> usageView.appendUsage(usage)); } } return true; }); if (getUsageView(indicator, startSearchStamp) != null) { ApplicationManager.getApplication().invokeLater(() -> myUsageViewManager.showToolWindow(true), myProject.getDisposed()); } Disposer.dispose(findUsagesStartedBalloon); ApplicationManager.getApplication().invokeLater(() -> { if (findStartedBalloonShown.get()) { Balloon balloon = ToolWindowManager.getInstance(myProject).getToolWindowBalloon(ToolWindowId.FIND); if (balloon != null) { balloon.hide(); } } }, myProject.getDisposed()); } private void endSearchForUsages(@NotNull final AtomicBoolean findStartedBalloonShown) { assert !ApplicationManager.getApplication().isDispatchThread() : Thread.currentThread(); int usageCount = myUsageCountWithoutDefinition.get(); if (usageCount == 0) { if (myProcessPresentation.isShowNotFoundMessage()) { ApplicationManager.getApplication().invokeLater(() -> { if (myProcessPresentation.isCanceled()) { notifyByFindBalloon(null, MessageType.WARNING, Collections.singletonList("Usage search was canceled")); findStartedBalloonShown.set(false); return; } List<String> lines = new ArrayList<>(); lines.add(StringUtil.escapeXmlEntities(myPresentation.getSearchString())); lines.add(UsageViewBundle.message("search.result.nothing.in.0", StringUtil.escapeXmlEntities(myPresentation.getScopeText()))); if (myOutOfScopeUsages.get() != 0) { lines.add(UsageViewManagerImpl.outOfScopeMessage(myOutOfScopeUsages.get(), mySearchScopeToWarnOfFallingOutOf)); } if (myProcessPresentation.isShowFindOptionsPrompt()) { lines.add(createOptionsHtml(mySearchFor)); } MessageType type = myOutOfScopeUsages.get() == 0 ? MessageType.INFO : MessageType.WARNING; notifyByFindBalloon(createGotToOptionsListener(mySearchFor), type, lines); findStartedBalloonShown.set(false); }, ModalityState.NON_MODAL, myProject.getDisposed()); } } else if (usageCount == 1 && !myProcessPresentation.isShowPanelIfOnlyOneUsage()) { ApplicationManager.getApplication().invokeLater(() -> { Usage usage = myFirstUsage.get(); if (usage.canNavigate()) { usage.navigate(true); flashUsageScriptaculously(usage); } List<String> lines = new ArrayList<>(); lines.add("Only one usage found."); if (myOutOfScopeUsages.get() != 0) { lines.add(UsageViewManagerImpl.outOfScopeMessage(myOutOfScopeUsages.get(), mySearchScopeToWarnOfFallingOutOf)); } lines.add(createOptionsHtml(mySearchFor)); MessageType type = myOutOfScopeUsages.get() == 0 ? MessageType.INFO : MessageType.WARNING; notifyByFindBalloon(createGotToOptionsListener(mySearchFor), type, lines); }, ModalityState.NON_MODAL, myProject.getDisposed()); } else { final UsageViewEx usageView = myUsageViewRef.get(); usageView.searchFinished(); final List<String> lines; final HyperlinkListener hyperlinkListener; if (myOutOfScopeUsages.get() == 0 || getPsiElement(mySearchFor)==null) { lines = Collections.emptyList(); hyperlinkListener = null; } else { lines = Arrays.asList(UsageViewManagerImpl.outOfScopeMessage(myOutOfScopeUsages.get(), mySearchScopeToWarnOfFallingOutOf), createSearchInProjectHtml()); hyperlinkListener = createSearchInProjectListener(); } if (!myProcessPresentation.getLargeFiles().isEmpty() || myOutOfScopeUsages.get() != 0 || myProcessPresentation.searchIncludingProjectFileUsages() != null || !getUnloadedModulesBelongingToScope().isEmpty()) { ApplicationManager.getApplication().invokeLater(() -> { MessageType type = myOutOfScopeUsages.get() == 0 ? MessageType.INFO : MessageType.WARNING; notifyByFindBalloon(hyperlinkListener, type, lines); }, ModalityState.NON_MODAL, myProject.getDisposed()); } } UsageViewEx usageView = myUsageViewRef.get(); if (usageView != null) { usageView.waitForUpdateRequestsCompletion(); } if (myListener != null) { myListener.findingUsagesFinished(usageView); } } @NotNull private static String mayHaveUsagesInUnloadedModulesMessage(@NotNull Collection<? extends UnloadedModuleDescription> unloadedModules) { String modulesText = unloadedModules.size() > 1 ? unloadedModules.size() + " unloaded modules" : "unloaded module '" + Objects .requireNonNull(ContainerUtil.getFirstItem(unloadedModules)).getName() + "'"; return "Occurrences in " + modulesText + " may be skipped. Load all modules and repeat the search to get complete results."; } }
package com.csmancala.core; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Transparency; import java.awt.image.BufferedImage; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import com.csmancala.component.GamePanel; import com.csmancala.file.ResourceLoader; import com.csmancala.run.Start; public class RenderGraphics { private static GamePanel gamePanel = Start.getMancala().getGamePanel(); public static void paintBackground(JPanel panel, Graphics2D g2D) { g2D.drawImage(ResourceLoader.TABLE_BACKGROUND, 0, 0, panel.getWidth(), panel.getHeight(), null); } private static int startX; private static int startY; private static int scaledWidth; private static int scaledHeight; private static double multiplier; private static float maxMultiplier = 0.7f; public static void paintMancalaBoard(Graphics2D g2D) { // paintMancalaBoardShadow(g2D); multiplier = (double)(gamePanel.getWidth() / (double)1920); if (multiplier > maxMultiplier && ((double)gamePanel.getHeight() / (double)gamePanel.getWidth() <= 0.5)) { multiplier = maxMultiplier; } scaledWidth = (int) (ResourceLoader.MANCALA_BOARD.getWidth() * multiplier); scaledHeight = (int) (ResourceLoader.MANCALA_BOARD.getHeight() * multiplier); startX = (int)(gamePanel.getWidth() - scaledWidth) / 2; startY = (int)(gamePanel.getHeight() - scaledHeight) / 2; BufferedImage scaledImage = scaleImage(ResourceLoader.MANCALA_BOARD, scaledWidth, scaledHeight, RenderingHints.VALUE_INTERPOLATION_BILINEAR, true); g2D.drawImage(scaledImage, startX, startY, null); updatePlayerNames(); updateButtons(); updateButtonText(); } private static void updateButtons() { Slot[][] board = Start.getMancala().getBoard().getSlotArray(); for (int y = 0; y < board[0].length; y++) { for (int x = 0; x < board.length; x++) { if (!(x == 0 && y == 1) && !(x == 7 && y == 0)) { if (board[x][y].isHovered) setButtonProperties(gamePanel.boardButtons[x][y], true); else setButtonProperties(gamePanel.boardButtons[x][y], false); } } } } private static void setButtonProperties(JButton b, boolean hovered) { BufferedImage goalImage = scaleImage(ResourceLoader.GOAL_BACKGROUND, (int) (ResourceLoader.GOAL_BACKGROUND.getWidth() * multiplier), (int) (ResourceLoader.GOAL_BACKGROUND.getHeight() * multiplier), RenderingHints.VALUE_INTERPOLATION_BILINEAR, true); BufferedImage slotImage = scaleImage(ResourceLoader.SLOT_BACKGROUND, (int) (ResourceLoader.SLOT_BACKGROUND.getWidth() * multiplier), (int) (ResourceLoader.SLOT_BACKGROUND.getHeight() * multiplier), RenderingHints.VALUE_INTERPOLATION_BILINEAR, true); BufferedImage goalHoveredImage = scaleImage(ResourceLoader.GOAL_HIGHLIGHT_BACKGROUND, (int) (ResourceLoader.GOAL_HIGHLIGHT_BACKGROUND.getWidth() * multiplier), (int) (ResourceLoader.GOAL_HIGHLIGHT_BACKGROUND.getHeight() * multiplier), RenderingHints.VALUE_INTERPOLATION_BILINEAR, true); BufferedImage slotHoveredImage = scaleImage(ResourceLoader.SLOT_HIGHLIGHT_BACKGROUND, (int) (ResourceLoader.SLOT_HIGHLIGHT_BACKGROUND.getWidth() * multiplier), (int) (ResourceLoader.SLOT_HIGHLIGHT_BACKGROUND.getHeight() * multiplier), RenderingHints.VALUE_INTERPOLATION_BILINEAR, true); Dimension goalSize = new Dimension(goalImage.getWidth(), goalImage.getHeight()); Dimension slotSize = new Dimension(slotImage.getWidth(), slotImage.getHeight()); Dimension goalHoveredSize = new Dimension(goalHoveredImage.getWidth(), goalHoveredImage.getHeight()); Dimension slotHoveredSize = new Dimension(slotHoveredImage.getWidth(), slotHoveredImage.getHeight()); ImageIcon goalIcon = new ImageIcon(goalImage); ImageIcon slotIcon = new ImageIcon(slotImage); ImageIcon goalHoveredIcon = new ImageIcon(goalHoveredImage); ImageIcon slotHoveredIcon = new ImageIcon(slotHoveredImage); if (b.equals(gamePanel.boardButtons[0][0])) { if (hovered) { gamePanel.boardButtons[0][0].setLocation((int)(startX + 60 - 7.5 * multiplier), (int)(startY + 50 - 7.5 * multiplier)); gamePanel.boardButtons[0][0].setIcon(goalHoveredIcon); gamePanel.boardButtons[0][0].setSize(goalHoveredSize); } else { gamePanel.boardButtons[0][0].setLocation((int)(startX + 60 * multiplier), (int)(startY + 50 * multiplier)); gamePanel.boardButtons[0][0].setIcon(goalIcon); gamePanel.boardButtons[0][0].setSize(goalSize); } } else if (b.equals(gamePanel.boardButtons[7][1])) { if (hovered) { gamePanel.boardButtons[7][1].setLocation((int)(startX + 1320 - 7.5 * multiplier), (int)(startY + 50 - 7.5 * multiplier)); gamePanel.boardButtons[7][1].setIcon(goalHoveredIcon); gamePanel.boardButtons[7][1].setSize(goalHoveredSize); } else { gamePanel.boardButtons[7][1].setLocation((int)(startX + 1320 * multiplier), (int)(startY + 50 * multiplier)); gamePanel.boardButtons[7][1].setIcon(goalIcon); gamePanel.boardButtons[7][1].setSize(goalSize); } } for (int y = 0; y < 2; y++) { for (int x = 1; x < 7; x++) { if (b.equals(gamePanel.boardButtons[x][y])) { if (y == 0) { if (hovered) { gamePanel.boardButtons[x][y].setLocation((int)(startX + (((x - 1) * 180) + 242 - 7.5) * multiplier), (int)(startY + ((50 - 7.5) * multiplier))); gamePanel.boardButtons[x][y].setIcon(slotHoveredIcon); gamePanel.boardButtons[x][y].setSize(slotHoveredSize); } else { gamePanel.boardButtons[x][y].setLocation((int)(startX + (((x - 1) * 180) + 242) * multiplier), (int)(startY + (50 * multiplier))); gamePanel.boardButtons[x][y].setIcon(slotIcon); gamePanel.boardButtons[x][y].setSize(slotSize); } } else { if (hovered) { gamePanel.boardButtons[x][y].setLocation((int)(startX + (((x - 1) * 180) + 242 - 7.5) * multiplier), (int)(startY + ((258 - 7.5) * multiplier))); gamePanel.boardButtons[x][y].setIcon(slotHoveredIcon); gamePanel.boardButtons[x][y].setSize(slotHoveredSize); } else { gamePanel.boardButtons[x][y].setLocation((int)(startX + (((x - 1) * 180) + 242) * multiplier), (int)(startY + 258 * multiplier)); gamePanel.boardButtons[x][y].setIcon(slotIcon); gamePanel.boardButtons[x][y].setSize(slotSize); } } } } } } private static void updatePlayerNames() { JLabel p1Name = gamePanel.player1Name; JLabel p2Name = gamePanel.player1Name; Player p1 = Start.getMancala().getBoard().getPlayer1(); Player p2 = Start.getMancala().getBoard().getPlayer2(); Player currentPlayer = Start.getMancala().getCurrentPlayer(); if (p1 != null && !p1Name.equals(p1.getName())) { p1Name.setText(p1.getName()); int style = Font.PLAIN; if (p1Name.equals(currentPlayer.getName())) { style = Font.BOLD; } p1Name.setFont(new Font(p1Name.getText(), style, (int)(72 * multiplier))); } p1Name.setSize(new Dimension(p1Name.getFontMetrics(p1Name.getFont()).stringWidth(p1Name.getText()), p1Name.getFontMetrics(p1Name.getFont()).getHeight())); p1Name.setLocation(startX, startY - (int)(70 * multiplier)); if (p2 != null && !p2Name.equals(p2.getName())) { p2Name.setText(p2.getName()); int style = Font.PLAIN; if (p2Name.equals(currentPlayer.getName())) { style = Font.BOLD; } p2Name.setFont(new Font(p2Name.getText(), style, (int)(72 * multiplier))); } p2Name.setSize(new Dimension(p2Name.getFontMetrics(p2Name.getFont()).stringWidth(p2Name.getText()), p2Name.getFontMetrics(p2Name.getFont()).getHeight())); p2Name.setLocation(startX + scaledWidth - p2Name.getWidth(), startY + scaledHeight + (int)(70 * multiplier)); } public static void updateButtonText() { gamePanel.boardButtons[0][0].setText(Integer.toString(Start.getMancala().getBoard().getPlayer1().getGoal().getStoneAmount())); gamePanel.boardButtons[7][1].setText(Integer.toString(Start.getMancala().getBoard().getPlayer2().getGoal().getStoneAmount())); for (int y = 0; y < 2; y++) { for (int x = 1; x < 7; x++) { gamePanel.boardButtons[x][y].setText(Integer.toString(Start.getMancala().getBoard().getSlotArray()[x][y].getStoneAmount())); } } } public static BufferedImage scaleImage(BufferedImage img, int targetWidth, int targetHeight, Object hint, boolean higherQuality) { int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB; BufferedImage ret = (BufferedImage) img; int w, h; if (higherQuality) { // Use multi-step technique: start with original size, then // scale down in multiple passes with drawImage() // until the target size is reached w = img.getWidth(); if (w < targetWidth) { w = targetWidth; } h = img.getHeight(); if (h < targetHeight) { h = targetHeight; } } else { // Use one-step technique: scale directly from original // size to target size with a single drawImage() call w = targetWidth; h = targetHeight; } do { if (higherQuality && w > targetWidth) { w >>= 1; if (w < targetWidth) { w = targetWidth; } } if (higherQuality && h > targetHeight) { h >>= 1; if (h < targetHeight) { h = targetHeight; } } BufferedImage tmp = new BufferedImage(w, h, type); Graphics2D g2 = tmp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint); g2.drawImage(ret, 0, 0, w, h, null); ret = tmp; } while (w != targetWidth || h != targetHeight); return ret; } }
package com.digero.maestro.view; import info.clearthought.layout.TableLayout; import info.clearthought.layout.TableLayoutConstants; import java.awt.Font; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JPanel; import com.digero.common.abc.LotroInstrument; import com.digero.common.midi.MidiConstants; import com.digero.common.midi.Note; import com.digero.common.midi.NoteFilterSequencerWrapper; import com.digero.common.midi.SequencerEvent; import com.digero.common.midi.SequencerListener; import com.digero.common.midi.SequencerProperty; import com.digero.common.midi.SequencerWrapper; import com.digero.common.util.ICompileConstants; import com.digero.common.util.IDiscardable; import com.digero.common.util.Util; import com.digero.common.view.ColorTable; import com.digero.maestro.abc.AbcPart; import com.digero.maestro.abc.AbcPartEvent; import com.digero.maestro.abc.AbcPartListener; import com.digero.maestro.abc.LotroDrumInfo; import com.digero.maestro.midi.NoteEvent; import com.digero.maestro.midi.TrackInfo; @SuppressWarnings("serial") public class DrumPanel extends JPanel implements IDiscardable, TableLayoutConstants, ICompileConstants { // 0 1 2 3 private static final int HGAP = 4; private static final int GUTTER_WIDTH = TrackPanel.GUTTER_WIDTH; private static final int COMBO_WIDTH = 122; private static final int TITLE_WIDTH = TrackPanel.TITLE_WIDTH + TrackPanel.CONTROL_WIDTH - COMBO_WIDTH; private static final double[] LAYOUT_COLS = new double[] { GUTTER_WIDTH, TITLE_WIDTH, COMBO_WIDTH, FILL }; private static final double[] LAYOUT_ROWS = new double[] { PREFERRED }; private TrackInfo trackInfo; private NoteFilterSequencerWrapper seq; private SequencerWrapper abcSequencer; private AbcPart abcPart; private int drumId; private boolean isAbcPreviewMode; private JPanel gutter; private JCheckBox checkBox; private JComboBox<LotroDrumInfo> drumComboBox; private DrumNoteGraph noteGraph; private TrackVolumeBar trackVolumeBar; private ActionListener trackVolumeBarListener; public DrumPanel(TrackInfo info, NoteFilterSequencerWrapper sequencer, AbcPart part, int drumNoteId, SequencerWrapper abcSequencer_, TrackVolumeBar trackVolumeBar_) { super(new TableLayout(LAYOUT_COLS, LAYOUT_ROWS)); this.trackInfo = info; this.seq = sequencer; this.abcSequencer = abcSequencer_; this.abcPart = part; this.drumId = drumNoteId; this.trackVolumeBar = trackVolumeBar_; TableLayout tableLayout = (TableLayout) getLayout(); tableLayout.setHGap(HGAP); gutter = new JPanel((LayoutManager) null); gutter.setOpaque(false); checkBox = new JCheckBox(); checkBox.setSelected(abcPart.isDrumEnabled(trackInfo.getTrackNumber(), drumId)); checkBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { abcPart.setDrumEnabled(trackInfo.getTrackNumber(), drumId, checkBox.isSelected()); } }); checkBox.setOpaque(false); String title = trackInfo.getTrackNumber() + ". " + trackInfo.getName(); String instr; if (info.isDrumTrack()) instr = MidiConstants.getDrumName(drumId); else { instr = Note.fromId(drumNoteId).abc; checkBox.setFont(checkBox.getFont().deriveFont(Font.BOLD)); } checkBox.setToolTipText("<html><b>" + title + "</b><br>" + instr + "</html>"); instr = Util.ellipsis(instr, TITLE_WIDTH, checkBox.getFont()); checkBox.setText(instr); drumComboBox = new JComboBox<LotroDrumInfo>(LotroDrumInfo.ALL_DRUMS.toArray(new LotroDrumInfo[0])); drumComboBox.setSelectedItem(getSelectedDrum()); drumComboBox.setMaximumRowCount(20); drumComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { LotroDrumInfo selected = (LotroDrumInfo) drumComboBox.getSelectedItem(); abcPart.getDrumMap(trackInfo.getTrackNumber()).set(drumId, selected.note.id); } }); seq.addChangeListener(sequencerListener); if (abcSequencer != null) abcSequencer.addChangeListener(sequencerListener); abcPart.addAbcListener(abcPartListener); noteGraph = new DrumNoteGraph(seq, trackInfo); noteGraph.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, ColorTable.OCTAVE_LINE.get())); noteGraph.addMouseListener(new MouseAdapter() { private int soloAbcTrack = -1; private int soloAbcDrumId = -1; private int soloTrack = -1; private int soloDrumId = -1; @Override public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) { int trackNumber = trackInfo.getTrackNumber(); if (isAbcPreviewMode() && abcSequencer instanceof NoteFilterSequencerWrapper) { if (abcPart.isTrackEnabled(trackNumber)) { soloAbcTrack = abcPart.getPreviewSequenceTrackNumber(); Note soloDrumNote = abcPart.mapNote(trackNumber, drumId); soloAbcDrumId = (soloDrumNote == null) ? -1 : soloDrumNote.id; } if (soloAbcTrack >= 0 && soloAbcDrumId >= 0) { ((NoteFilterSequencerWrapper) abcSequencer).setNoteSolo(soloAbcTrack, soloAbcDrumId, true); } } else { soloTrack = trackNumber; soloDrumId = drumId; seq.setNoteSolo(trackNumber, drumId, true); } } } @Override public void mouseReleased(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) { if (soloAbcTrack >= 0 && soloAbcDrumId >= 0 && abcSequencer instanceof NoteFilterSequencerWrapper) { ((NoteFilterSequencerWrapper) abcSequencer).setNoteSolo(soloAbcTrack, soloAbcDrumId, false); } soloAbcTrack = -1; soloAbcDrumId = -1; if (soloTrack >= 0 && soloDrumId >= 0) { seq.setNoteSolo(soloTrack, soloDrumId, false); } soloTrack = -1; soloDrumId = -1; } } }); if (trackVolumeBar != null) { trackVolumeBar.addActionListener(trackVolumeBarListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateState(); } }); } addPropertyChangeListener("enabled", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { updateState(); } }); add(gutter, "0, 0"); add(checkBox, "1, 0"); add(drumComboBox, "2, 0, f, c"); add(noteGraph, "3, 0"); updateState(); } @Override public void discard() { noteGraph.discard(); abcPart.removeAbcListener(abcPartListener); seq.removeChangeListener(sequencerListener); if (abcSequencer != null) abcSequencer.removeChangeListener(sequencerListener); if (trackVolumeBar != null) trackVolumeBar.removeActionListener(trackVolumeBarListener); } private AbcPartListener abcPartListener = new AbcPartListener() { @Override public void abcPartChanged(AbcPartEvent e) { if (e.isNoteGraphRelated()) { checkBox.setEnabled(abcPart.isTrackEnabled(trackInfo.getTrackNumber())); checkBox.setSelected(abcPart.isDrumEnabled(trackInfo.getTrackNumber(), drumId)); drumComboBox.setSelectedItem(getSelectedDrum()); updateState(); } } }; private SequencerListener sequencerListener = new SequencerListener() { @Override public void propertyChanged(SequencerEvent evt) { if (evt.getProperty() == SequencerProperty.TRACK_ACTIVE) updateState(); } }; private void updateState() { boolean abcPreviewMode = isAbcPreviewMode(); int trackNumber = trackInfo.getTrackNumber(); boolean trackEnabled = abcPart.isTrackEnabled(trackNumber); boolean noteEnabled = abcPart.isDrumEnabled(trackNumber, drumId); boolean noteEnabledOtherPart = false; boolean noteActive; if (abcPreviewMode) { noteActive = false; } else { noteActive = seq.isTrackActive(trackNumber) && seq.isNoteActive(drumId); } boolean isDraggingVolumeBar = (trackVolumeBar != null) && trackVolumeBar.isDragging(); noteGraph.setShowingNoteVelocity(isDraggingVolumeBar); if (isDraggingVolumeBar) noteGraph.setDeltaVolume(trackVolumeBar.getDeltaVolume()); else noteGraph.setDeltaVolume(abcPart.getTrackVolumeAdjust(trackInfo.getTrackNumber())); for (AbcPart part : abcPart.getOwnerProject().getAllParts()) { if (part.isTrackEnabled(trackNumber)) { if (part != this.abcPart && part.isDrumEnabled(trackNumber, drumId)) noteEnabledOtherPart = true; if (abcPreviewMode) { Note drumNote = part.mapNote(trackNumber, drumId); if (drumNote != null && abcSequencer.isTrackActive(part.getPreviewSequenceTrackNumber()) && abcSequencer.isNoteActive(drumNote.id)) { noteActive = true; } } } } gutter.setOpaque(noteEnabled || noteEnabledOtherPart); if (noteEnabled) gutter.setBackground(ColorTable.PANEL_HIGHLIGHT.get()); else if (noteEnabledOtherPart) gutter.setBackground(ColorTable.PANEL_HIGHLIGHT_OTHER_PART.get()); noteGraph.setShowingAbcNotesOn(noteActive); checkBox.setEnabled(trackEnabled); drumComboBox.setEnabled(trackEnabled); drumComboBox.setVisible(abcPart.getInstrument() == LotroInstrument.DRUMS); if (!noteActive) { noteGraph.setNoteColor(ColorTable.NOTE_DRUM_OFF); noteGraph.setBadNoteColor(ColorTable.NOTE_DRUM_OFF); setBackground(ColorTable.GRAPH_BACKGROUND_OFF.get()); checkBox.setForeground(ColorTable.PANEL_TEXT_OFF.get()); } else if (trackEnabled && abcPart.isDrumEnabled(trackNumber, drumId)) { noteGraph.setNoteColor(ColorTable.NOTE_DRUM_ENABLED); noteGraph.setBadNoteColor(ColorTable.NOTE_BAD_ENABLED); setBackground(ColorTable.GRAPH_BACKGROUND_ENABLED.get()); checkBox.setForeground(ColorTable.PANEL_TEXT_ENABLED.get()); } else { noteGraph.setNoteColor(ColorTable.NOTE_DRUM_OFF); noteGraph.setBadNoteColor(ColorTable.NOTE_BAD_OFF); setBackground(ColorTable.GRAPH_BACKGROUND_OFF.get()); checkBox.setForeground(ColorTable.PANEL_TEXT_OFF.get()); } } public void setAbcPreviewMode(boolean isAbcPreviewMode) { if (this.isAbcPreviewMode != isAbcPreviewMode) { this.isAbcPreviewMode = isAbcPreviewMode; updateState(); } } private boolean isAbcPreviewMode() { return abcSequencer != null && isAbcPreviewMode; } private LotroDrumInfo getSelectedDrum() { return LotroDrumInfo.getById(abcPart.getDrumMap(trackInfo.getTrackNumber()).get(drumId)); } private class DrumNoteGraph extends NoteGraph { private boolean showingAbcNotesOn = true; public DrumNoteGraph(SequencerWrapper sequencer, TrackInfo trackInfo) { super(sequencer, trackInfo, -1, 1, 2, 5); } public void setShowingAbcNotesOn(boolean showingAbcNotesOn) { if (this.showingAbcNotesOn != showingAbcNotesOn) { this.showingAbcNotesOn = showingAbcNotesOn; repaint(); } } @Override protected int transposeNote(int noteId) { return 0; } @Override protected boolean isNotePlayable(int noteId) { return abcPart.isDrumPlayable(trackInfo.getTrackNumber(), drumId); } @Override protected boolean isShowingNotesOn() { if (sequencer.isRunning()) return sequencer.isTrackActive(trackInfo.getTrackNumber()); if (abcSequencer != null && abcSequencer.isRunning()) return showingAbcNotesOn; return false; } @Override protected boolean isNoteVisible(NoteEvent ne) { return ne.note.id == drumId; } } }
package com.ecyrd.jspwiki; import java.util.Properties; import org.apache.log4j.Category; import java.io.File; import java.io.BufferedReader; import java.io.InputStreamReader; import org.apache.oro.text.*; import org.apache.oro.text.regex.*; import java.util.Collection; import java.util.ArrayList; import java.util.Date; import java.text.SimpleDateFormat; /** * This class implements a simple RCS file provider. NOTE: You MUST * have the RCS package installed for this to work. They must also * be in your path... * * <P> * The RCS file provider extends from the FileSystemProvider, which * means that it provides the pages in the same way. The only difference * is that it implements the version history commands, and also in each * checkin it writes the page to the RCS repository as well. * * @author Janne Jalkanen */ // FIXME: Not all commands read their format from the property file yet. public class RCSFileProvider extends FileSystemProvider { private String m_checkinCommand = "ci -q -m\"author=%u\" -l -t-none %s"; private String m_checkoutCommand = "co -l %s"; private String m_logCommand = "rlog -zLT -r %s"; private String m_fullLogCommand = "rlog -zLT %s"; private String m_checkoutVersionCommand = "co -p -r1.%v %s"; private static final Category log = Category.getInstance(RCSFileProvider.class); public static final String PROP_CHECKIN = "jspwiki.rcsFileProvider.checkinCommand"; public static final String PROP_CHECKOUT = "jspwiki.rcsFileProvider.checkoutCommand"; public static final String PROP_LOG = "jspwiki.rcsFileProvider.logCommand"; public static final String PROP_FULLLOG = "jspwiki.rcsFileProvider.fullLogCommand"; public static final String PROP_CHECKOUTVERSION = "jspwiki.rcsFileProvider.checkoutVersionCommand"; private static final String PATTERN_DATE = "^date:\\s*(.*)[\\+\\-;]\\d+;"; private static final String PATTERN_AUTHOR = "^\"?author=([\\w\\.\\s\\+\\.\\%]*)\"?"; private static final String PATTERN_REVISION = "^revision \\d+\\.(\\d+)"; private static final String RCSFMT_DATE = "yyyy-MM-dd HH:mm:ss"; public void initialize( Properties props ) throws NoRequiredPropertyException, IOException { log.debug("Initing RCS"); super.initialize( props ); m_checkinCommand = props.getProperty( PROP_CHECKIN, m_checkinCommand ); m_checkoutCommand = props.getProperty( PROP_CHECKOUT, m_checkoutCommand ); m_logCommand = props.getProperty( PROP_LOG, m_logCommand ); m_fullLogCommand = props.getProperty( PROP_FULLLOG, m_fullLogCommand ); m_checkoutVersionCommand = props.getProperty( PROP_CHECKOUTVERSION, m_checkoutVersionCommand ); File rcsdir = new File( getPageDirectory(), "RCS" ); if( !rcsdir.exists() ) rcsdir.mkdirs(); log.debug("checkin="+m_checkinCommand); log.debug("checkout="+m_checkoutCommand); log.debug("log="+m_logCommand); log.debug("fulllog="+m_fullLogCommand); log.debug("checkoutversion="+m_checkoutVersionCommand); } // NB: This is a very slow method. public WikiPage getPageInfo( String page, int version ) { PatternMatcher matcher = new Perl5Matcher(); PatternCompiler compiler = new Perl5Compiler(); PatternMatcherInput input; WikiPage info = super.getPageInfo( page, version ); try { String cmd = m_fullLogCommand; cmd = TextUtil.replaceString( cmd, "%s", mangleName(page)+FILE_EXT ); Process process = Runtime.getRuntime().exec( cmd, null, new File(getPageDirectory()) ); // FIXME: Should this use encoding as well? BufferedReader stdout = new BufferedReader( new InputStreamReader(process.getInputStream() ) ); String line; Pattern headpattern = compiler.compile( PATTERN_REVISION ); // This complicated pattern is required, since on Linux RCS adds // quotation marks, but on Windows, it does not. Pattern userpattern = compiler.compile( PATTERN_AUTHOR ); Pattern datepattern = compiler.compile( PATTERN_DATE ); SimpleDateFormat rcsdatefmt = new SimpleDateFormat( RCSFMT_DATE ); boolean found = false; while( (line = stdout.readLine()) != null ) { if( matcher.contains( line, headpattern ) ) { MatchResult result = matcher.getMatch(); int vernum = Integer.parseInt( result.group(1) ); if( vernum == version || version == WikiPageProvider.LATEST_VERSION ) { info.setVersion( vernum ); found = true; } } else if( matcher.contains( line, datepattern ) && found ) { MatchResult result = matcher.getMatch(); Date d = rcsdatefmt.parse( result.group(1) ); if( d != null ) { info.setLastModified( d ); } else { log.info("WikiPage "+info.getName()+ " has null modification date for version "+ version); } } else if( matcher.contains( line, userpattern ) && found ) { MatchResult result = matcher.getMatch(); info.setAuthor( TextUtil.urlDecodeUTF8(result.group(1)) ); } else if( found && line.startsWith(" { // End of line sign from RCS break; } } // Especially with certain versions of RCS on Windows, // process.waitFor() hangs unless you read all of the // standard output. So we make sure it's all emptied. while( (line = stdout.readLine()) != null ) { } process.waitFor(); } catch( Exception e ) { // This also occurs when 'info' was null. log.warn("Failed to read RCS info",e); } return info; } public String getPageText( String page, int version ) { String result = null; // Let parent handle latest fetches, since the FileSystemProvider // can do the file reading just as well. if( version == WikiPageProvider.LATEST_VERSION ) return super.getPageText( page, version ); log.debug("Fetching specific version "+version+" of page "+page); try { String cmd = m_checkoutVersionCommand; cmd = TextUtil.replaceString( cmd, "%s", mangleName(page)+FILE_EXT ); cmd = TextUtil.replaceString( cmd, "%v", Integer.toString(version ) ); log.debug("Command = '"+cmd+"'"); Process process = Runtime.getRuntime().exec( cmd, null, new File(getPageDirectory()) ); result = FileUtil.readContents( process.getInputStream(), m_encoding ); process.waitFor(); log.debug("Done, returned = "+process.exitValue()); } catch( Exception e ) { log.error("RCS checkout failed",e); } return result; } /** * Puts the page into RCS and makes sure there is a fresh copy in * the directory as well. */ public void putPageText( WikiPage page, String text ) { String pagename = page.getName(); // Writes it in the dir. super.putPageText( page, text ); log.debug( "Checking in text..." ); try { String cmd = m_checkinCommand; String author = page.getAuthor(); if( author == null ) author = "unknown"; cmd = TextUtil.replaceString( cmd, "%s", mangleName(pagename)+FILE_EXT ); cmd = TextUtil.replaceString( cmd, "%u", TextUtil.urlEncodeUTF8(author) ); log.debug("Command = '"+cmd+"'"); Process process = Runtime.getRuntime().exec( cmd, null, new File(getPageDirectory()) ); process.waitFor(); log.debug("Done, returned = "+process.exitValue()); } catch( Exception e ) { log.error("RCS checkin failed",e); } } // FIXME: Put the rcs date formats into properties as well. public Collection getVersionHistory( String page ) { PatternMatcher matcher = new Perl5Matcher(); PatternCompiler compiler = new Perl5Compiler(); PatternMatcherInput input; log.debug("Getting RCS version history"); ArrayList list = new ArrayList(); SimpleDateFormat rcsdatefmt = new SimpleDateFormat( RCSFMT_DATE ); try { Pattern revpattern = compiler.compile( PATTERN_REVISION ); Pattern datepattern = compiler.compile( PATTERN_DATE ); // This complicated pattern is required, since on Linux RCS adds // quotation marks, but on Windows, it does not. Pattern userpattern = compiler.compile( PATTERN_AUTHOR ); String cmd = TextUtil.replaceString( m_fullLogCommand, "%s", mangleName(page)+FILE_EXT ); Process process = Runtime.getRuntime().exec( cmd, null, new File(getPageDirectory()) ); // FIXME: Should this use encoding as well? BufferedReader stdout = new BufferedReader( new InputStreamReader(process.getInputStream()) ); String line; WikiPage info = null; while( (line = stdout.readLine()) != null ) { if( matcher.contains( line, revpattern ) ) { info = new WikiPage( page ); MatchResult result = matcher.getMatch(); int vernum = Integer.parseInt( result.group(1) ); info.setVersion( vernum ); list.add( info ); } if( matcher.contains( line, datepattern ) ) { MatchResult result = matcher.getMatch(); Date d = rcsdatefmt.parse( result.group(1) ); info.setLastModified( d ); } if( matcher.contains( line, userpattern ) ) { MatchResult result = matcher.getMatch(); info.setAuthor( TextUtil.urlDecodeUTF8(result.group(1)) ); } } process.waitFor(); } catch( Exception e ) { log.error( "RCS log failed", e ); } return list; } }
// Kyle Russell // AUT University 2015 package com.graphi.plugins; import com.graphi.display.LayoutPanel; public class AbstractPlugin implements Plugin { private String name; private String description; private LayoutPanel panel; @Override public String getPluginName() { return name; } @Override public String getPluginDescription() { return description; } @Override public LayoutPanel load() { return panel; } }
package com.maddyhome.idea.vim; import com.intellij.ide.DataManager; import com.intellij.ide.IdeEventQueue; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.UndoConfirmationPolicy; import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.ActionPlan; import com.intellij.openapi.editor.actionSystem.DocCommandGroupId; import com.intellij.openapi.editor.actionSystem.TypedActionHandler; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.ListPopup; import com.maddyhome.idea.vim.action.DuplicableOperatorAction; import com.maddyhome.idea.vim.action.change.VimRepeater; import com.maddyhome.idea.vim.action.macro.ToggleRecordingAction; import com.maddyhome.idea.vim.action.motion.search.SearchEntryFwdAction; import com.maddyhome.idea.vim.action.motion.search.SearchEntryRevAction; import com.maddyhome.idea.vim.command.*; import com.maddyhome.idea.vim.extension.VimExtensionHandler; import com.maddyhome.idea.vim.group.ChangeGroup; import com.maddyhome.idea.vim.group.RegisterGroup; import com.maddyhome.idea.vim.group.visual.VimSelection; import com.maddyhome.idea.vim.group.visual.VisualGroupKt; import com.maddyhome.idea.vim.handler.EditorActionHandlerBase; import com.maddyhome.idea.vim.helper.*; import com.maddyhome.idea.vim.key.*; import com.maddyhome.idea.vim.listener.SelectionVimListenerSuppressor; import com.maddyhome.idea.vim.listener.VimListenerSuppressor; import com.maddyhome.idea.vim.option.OptionsManager; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.util.List; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import static com.intellij.openapi.actionSystem.CommonDataKeys.*; import static com.intellij.openapi.actionSystem.PlatformDataKeys.PROJECT_FILE_DIRECTORY; /** * This handlers every keystroke that the user can argType except those that are still valid hotkeys for various Idea * actions. This is a singleton. */ public class KeyHandler { /** * Returns a reference to the singleton instance of this class * * @return A reference to the singleton */ @NotNull public static KeyHandler getInstance() { if (instance == null) { instance = new KeyHandler(); } return instance; } /** * Creates an instance */ private KeyHandler() { } /** * Sets the original key handler * * @param origHandler The original key handler */ public void setOriginalHandler(TypedActionHandler origHandler) { this.origHandler = origHandler; } /** * Gets the original key handler * * @return The original key handler */ public TypedActionHandler getOriginalHandler() { return origHandler; } public static void executeVimAction(@NotNull Editor editor, @NotNull EditorActionHandlerBase cmd, DataContext context) { CommandProcessor.getInstance() .executeCommand(editor.getProject(), () -> cmd.execute(editor, getProjectAwareDataContext(editor, context)), cmd.getId(), DocCommandGroupId.noneGroupId(editor.getDocument()), UndoConfirmationPolicy.DEFAULT, editor.getDocument()); } /** * Execute an action * * @param action The action to execute * @param context The context to run it in */ public static boolean executeAction(@NotNull AnAction action, @NotNull DataContext context) { final AnActionEvent event = new AnActionEvent(null, context, ActionPlaces.ACTION_SEARCH, action.getTemplatePresentation(), ActionManager.getInstance(), 0); if (action instanceof ActionGroup && !((ActionGroup)action).canBePerformed(context)) { // Some of the AcitonGroups should not be performed, but shown as a popup ListPopup popup = JBPopupFactory.getInstance() .createActionGroupPopup(event.getPresentation().getText(), (ActionGroup)action, context, false, null, -1); Component component = context.getData(PlatformDataKeys.CONTEXT_COMPONENT); if (component != null) { Window window = SwingUtilities.getWindowAncestor(component); if (window != null) { popup.showInCenterOf(window); } return true; } popup.showInFocusCenter(); return true; } else { // beforeActionPerformedUpdate should be called to update the action. It fixes some rider-specific problems // because rider use async update method. See VIM-1819 action.beforeActionPerformedUpdate(event); if (event.getPresentation().isEnabled()) { action.actionPerformed(event); return true; } } return false; } public void startDigraphSequence(@NotNull Editor editor) { final CommandState editorState = CommandState.getInstance(editor); editorState.startDigraphSequence(); } public void startLiteralSequence(@NotNull Editor editor) { final CommandState editorState = CommandState.getInstance(editor); editorState.startLiteralSequence(); } /** * This is the main key handler for the Vim plugin. Every keystroke not handled directly by Idea is sent here for * processing. * * @param editor The editor the key was typed into * @param key The keystroke typed by the user * @param context The data context */ public void handleKey(@NotNull Editor editor, @NotNull KeyStroke key, @NotNull DataContext context) { handleKey(editor, key, context, true); } /** * Invoked before acquiring a write lock and actually handling the keystroke. * <p> * Drafts an optional {@link ActionPlan} that will be used as a base for zero-latency rendering in editor. * * @param editor The editor the key was typed into * @param key The keystroke typed by the user * @param context The data context * @param plan The current action plan */ public void beforeHandleKey(@NotNull Editor editor, @NotNull KeyStroke key, @NotNull DataContext context, @NotNull ActionPlan plan) { final CommandState.Mode mode = CommandState.getInstance(editor).getMode(); if (mode == CommandState.Mode.INSERT || mode == CommandState.Mode.REPLACE) { VimPlugin.getChange().beforeProcessKey(editor, context, key, plan); } } public void handleKey(@NotNull Editor editor, @NotNull KeyStroke key, @NotNull DataContext context, boolean allowKeyMappings) { VimPlugin.clearError(); // All the editor actions should be performed with top level editor!!! // Be careful: all the EditorActionHandler implementation should correctly process InjectedEditors editor = HelperKt.getTopLevelEditor(editor); final CommandState editorState = CommandState.getInstance(editor); // If this is a "regular" character keystroke, get the character char chKey = key.getKeyChar() == KeyEvent.CHAR_UNDEFINED ? 0 : key.getKeyChar(); final boolean isRecording = editorState.isRecording(); boolean shouldRecord = true; if (!waitCommandFinish(editor) && allowKeyMappings && handleKeyMapping(editor, key, context)) { if (editorState.getMappingMode() != MappingMode.OP_PENDING || currentCmd.isEmpty() || currentCmd.peek().getArgument() == null || Objects.requireNonNull(currentCmd.peek().getArgument()).getType() != Argument.Type.OFFSETS) { return; } } else if (isCommandCount(chKey, editorState)) { editorState.setCount((editorState.getCount() * 10) + (chKey - '0')); } else if (isDeleteCommandCount(key, editorState)) { editorState.setCount(editorState.getCount() / 10); } else if (isEditorReset(key, editorState)) { handleEditorReset(editor, key, context, editorState); } // If we got this far the user is entering a command or supplying an argument to an entered command. // First let's check to see if we are at the point of expecting a single character argument to a command. else if (editorState.getCurrentArgumentType() == Argument.Type.CHARACTER) { handleCharArgument(key, chKey); } // If we are this far, then the user must be entering a command or a non-single-character argument // to an entered command. Let's figure out which it is else { // For debugging purposes we track the keys entered for this command editorState.addKey(key); if (handleDigraph(editor, key, context, editorState)) return; // Ask the key/action tree if this is an appropriate key at this point in the command and if so, // return the node matching this keystroke Node node = editorState.getCurrentNode().get(key); node = mapOpCommand(key, node, editorState); if (node instanceof CommandNode) { handleCommandNode(editor, context, key, (CommandNode) node, editorState); } else if (node instanceof CommandPartNode) { editorState.setCurrentNode((CommandPartNode) node); } else { // If we are in insert/replace mode send this key in for processing if (editorState.getMode() == CommandState.Mode.INSERT || editorState.getMode() == CommandState.Mode.REPLACE) { if (!VimPlugin.getChange().processKey(editor, context, key)) { shouldRecord = false; } } else if (editorState.getMode() == CommandState.Mode.SELECT) { if (!VimPlugin.getChange().processKeyInSelectMode(editor, context, key)) { shouldRecord = false; } } else if (editorState.getMappingMode() == MappingMode.CMD_LINE) { if (!VimPlugin.getProcess().processExKey(editor, key)) { shouldRecord = false; } } // If we get here then the user has entered an unrecognized series of keystrokes else { state = State.BAD_COMMAND; } partialReset(editor); } } // Do we have a fully entered command at this point? If so, lets execute it if (state == State.READY) { executeCommand(editor, key, context, editorState); } else if (state == State.BAD_COMMAND) { if (editorState.getMappingMode() == MappingMode.OP_PENDING) { editorState.popState(); } VimPlugin.indicateError(); reset(editor); } else if (isRecording && shouldRecord) { VimPlugin.getRegister().recordKeyStroke(key); } } private boolean waitCommandFinish(@NotNull Editor editor) { return !(CommandState.getInstance(editor).getCurrentNode() instanceof RootNode); } /** * See the description for {@link com.maddyhome.idea.vim.action.DuplicableOperatorAction} */ private Node mapOpCommand(KeyStroke key, Node node, @NotNull CommandState editorState) { if (editorState.getMappingMode() == MappingMode.OP_PENDING && !currentCmd.empty()) { EditorActionHandlerBase action = currentCmd.peek().getAction(); if (action instanceof DuplicableOperatorAction && ((DuplicableOperatorAction)action).getDuplicateWith() == key.getKeyChar()) { return editorState.getCurrentNode().get(KeyStroke.getKeyStroke('_')); } } return node; } private static <T> boolean isPrefix(@NotNull List<T> list1, @NotNull List<T> list2) { if (list1.size() > list2.size()) { return false; } for (int i = 0; i < list1.size(); i++) { if (!list1.get(i).equals(list2.get(i))) { return false; } } return true; } private void handleEditorReset(@NotNull Editor editor, @NotNull KeyStroke key, @NotNull final DataContext context, CommandState editorState) { if (editorState.getCount() == 0 && editorState.getCurrentArgumentType() == null && currentCmd.size() == 0) { RegisterGroup register = VimPlugin.getRegister(); if (register.getCurrentRegister() == register.getDefaultRegister()) { if (key.getKeyCode() == KeyEvent.VK_ESCAPE) { CommandProcessor.getInstance() .executeCommand(editor.getProject(), () -> KeyHandler.executeAction("EditorEscape", context), "", null); } VimPlugin.indicateError(); } } reset(editor); ChangeGroup.resetCaret(editor, false); } private boolean handleKeyMapping(@NotNull final Editor editor, @NotNull final KeyStroke key, @NotNull final DataContext context) { final CommandState commandState = CommandState.getInstance(editor); if (state == State.CHAR_OR_DIGRAPH || isMappingDisabledForKey(key, commandState)) { return false; } commandState.stopMappingTimer(); final MappingMode mappingMode = commandState.getMappingMode(); final List<KeyStroke> previouslyUnhandledKeySequence = commandState.getMappingKeys(); final List<KeyStroke> currentlyUnhandledKeySequence = new ArrayList<>(previouslyUnhandledKeySequence); currentlyUnhandledKeySequence.add(key); final KeyMapping mapping = VimPlugin.getKey().getKeyMapping(mappingMode); // Returns true if any of these methods handle the key. False means that the key is unrelated to mapping and should // be processed as normal. return handleUnfinishedMappingSequence(editor, mapping, currentlyUnhandledKeySequence, key) || handleCompleteMappingSequence(editor, context, mapping, previouslyUnhandledKeySequence, currentlyUnhandledKeySequence, key) || handleAbandonedMappingSequence(editor, commandState, context, previouslyUnhandledKeySequence, currentlyUnhandledKeySequence); } private boolean isMappingDisabledForKey(@NotNull KeyStroke key, @NotNull CommandState commandState) { // "0" can be mapped, but the mapping isn't applied when entering a count. Other digits are always mapped, even when // entering a count. // See `:help :map-modes` return key.getKeyChar() == '0' && commandState.getCount() > 0; } private boolean handleUnfinishedMappingSequence(@NotNull Editor editor, @NotNull KeyMapping mapping, @NotNull List<KeyStroke> currentlyUnhandledKeySequence, @NotNull KeyStroke key) { // Is there at least one mapping that starts with the current sequence? This does not include complete matches, // unless a sequence is also a prefix for another mapping. We eagerly evaluate the shortest mapping, so even if a // mapping is a prefix, it will get evaluated when the next character is entered. // Note that currentlyUnhandledKeySequence is the same as the state after commandState.getMappingKeys().add(key). It // would be nice to tidy ths up if (!mapping.isPrefix(currentlyUnhandledKeySequence)) { return false; } // Save the unhandled key strokes until we either complete or abandon the sequence. final CommandState commandState = CommandState.getInstance(editor); commandState.getMappingKeys().add(key); // If the timeout option is set, set a timer that will abandon the sequence and replay the unhandled keys unmapped. // Every time a key is pressed and handled, the timer is stopped. E.g. if there is a mapping for "dweri", and the // user has typed "dw" wait for the timeout, and then replay "d" and "w" without any mapping (which will of course // delete a word) final Application application = ApplicationManager.getApplication(); if (!application.isUnitTestMode() && OptionsManager.INSTANCE.getTimeout().isSet()) { commandState.startMappingTimer(actionEvent -> application.invokeLater(() -> { final List<KeyStroke> unhandledKeys = new ArrayList<>(commandState.getMappingKeys()); commandState.getMappingKeys().clear(); // TODO: I'm not sure why we abandon plugin commands here // Would be useful to have a comment or a helpfully named helper method here if (editor.isDisposed() || unhandledKeys.get(0).equals(StringHelper.PlugKeyStroke)) { return; } for (KeyStroke keyStroke : unhandledKeys) { handleKey(editor, keyStroke, new EditorDataContext(editor), false); } }, ModalityState.stateForComponent(editor.getComponent()))); } return true; } private boolean handleCompleteMappingSequence(@NotNull Editor editor, DataContext context, @NotNull KeyMapping mapping, @NotNull List<KeyStroke> previouslyUnhandledKeySequence, @NotNull List<KeyStroke> currentlyUnhandledKeySequence, KeyStroke key) { // If the current sequence is a complete mapping, then evaluate it. If not, check if the previous sequence was a // mapping which was also a prefix, and evaluate it if so. final MappingInfo previousMappingInfo = mapping.get(previouslyUnhandledKeySequence); final MappingInfo currentMappingInfo = mapping.get(currentlyUnhandledKeySequence); final MappingInfo mappingInfo = currentMappingInfo != null ? currentMappingInfo : previousMappingInfo; if (mappingInfo == null) { return false; } final CommandState commandState = CommandState.getInstance(editor); commandState.getMappingKeys().clear(); final EditorDataContext currentContext = new EditorDataContext(editor); final List<KeyStroke> toKeys = mappingInfo.getToKeys(); final VimExtensionHandler extensionHandler = mappingInfo.getExtensionHandler(); if (toKeys != null) { final boolean fromIsPrefix = isPrefix(mappingInfo.getFromKeys(), toKeys); boolean first = true; for (KeyStroke keyStroke : toKeys) { final boolean recursive = mappingInfo.isRecursive() && !(first && fromIsPrefix); handleKey(editor, keyStroke, currentContext, recursive); first = false; } } else if (extensionHandler != null) { final CommandProcessor processor = CommandProcessor.getInstance(); final boolean isPendingMode = CommandState.getInstance(editor).getMappingMode() == MappingMode.OP_PENDING; Map<Caret, Integer> startOffsets = editor.getCaretModel().getAllCarets().stream().collect(Collectors.toMap(Function.identity(), Caret::getOffset)); if (extensionHandler.isRepeatable()) { VimRepeater.Extension.INSTANCE.clean(); } processor.executeCommand(editor.getProject(), () -> extensionHandler.execute(editor, context), "Vim " + extensionHandler.getClass().getSimpleName(), null); if (extensionHandler.isRepeatable()) { VimRepeater.Extension.INSTANCE.setLastExtensionHandler(extensionHandler); VimRepeater.Extension.INSTANCE.setArgumentCaptured(null); VimRepeater.INSTANCE.setRepeatHandler(true); } if (isPendingMode && !currentCmd.isEmpty() && currentCmd.peek().getArgument() == null) { Map<Caret, VimSelection> offsets = new HashMap<>(); for (Caret caret : editor.getCaretModel().getAllCarets()) { @Nullable Integer startOffset = startOffsets.get(caret); if (caret.hasSelection()) { final VimSelection vimSelection = VimSelection.Companion .create(UserDataManager.getVimSelectionStart(caret), caret.getOffset(), SelectionType.fromSubMode(CommandStateHelper.getSubMode(editor)), editor); offsets.put(caret, vimSelection); commandState.popState(); } else if (startOffset != null && startOffset != caret.getOffset()) { // Command line motions are always characterwise exclusive int endOffset = caret.getOffset(); if (startOffset < endOffset) { endOffset -= 1; } else { startOffset -= 1; } final VimSelection vimSelection = VimSelection.Companion .create(startOffset, endOffset, SelectionType.CHARACTER_WISE, editor); offsets.put(caret, vimSelection); try (VimListenerSuppressor.Locked ignored = SelectionVimListenerSuppressor.INSTANCE.lock()) { // Move caret to the initial offset for better undo action // This is not a necessary thing, but without it undo action look less convenient editor.getCaretModel().moveToOffset(startOffset); } } } if (!offsets.isEmpty()) { currentCmd.peek().setArgument(new Argument(offsets)); state = State.READY; } } } // If we've just evaluated the previous key sequence, make sure to also handle the current key if (previousMappingInfo == mappingInfo) { handleKey(editor, key, currentContext, true); } return true; } private boolean handleAbandonedMappingSequence(@NotNull Editor editor, @NotNull CommandState commandState, DataContext context, @NotNull List<KeyStroke> previouslyUnhandledKeySequence, @NotNull List<KeyStroke> currentlyUnhandledKeySequence) { // The user has terminated a mapping sequence with an unexpected key // E.g. if there is a mapping for "hello" and user enters command "help" the processing of "h", "e" and "l" will be // prevented by this handler. Make sure the currently unhandled keys are processed as normal. // If there are no previous keys to handle, do nothing if (previouslyUnhandledKeySequence.isEmpty()) { return false; } // Okay, look at the code below. Why is the first key handled separately? // Let's assume the next mappings: // - map ds j // - map I 2l // If user enters `dI`, the first `d` will be caught be this handler because it's a prefix for `ds` command. // After the user enters `I`, the caught `d` should be processed without mapping and the rest of keys // should be processed with mappings (to make I work) // Additionally, the <Plug>mappings are not executed if the are failed to map to somethings. // - map <Plug>iA someAction // - map I <Plug>i // For `IA` someAction should be executed. // But if the user types `Ib`, `<Plug>i` won't be executed again. Only `b` will be passed to keyHandler. commandState.getMappingKeys().clear(); if (currentlyUnhandledKeySequence.get(0).equals(StringHelper.PlugKeyStroke)) { handleKey(editor, currentlyUnhandledKeySequence.get(currentlyUnhandledKeySequence.size() - 1), context, true); } else { handleKey(editor, currentlyUnhandledKeySequence.get(0), context, false); for (KeyStroke keyStroke : currentlyUnhandledKeySequence.subList(1, currentlyUnhandledKeySequence.size())) { handleKey(editor, keyStroke, context, true); } } return true; } private boolean isDeleteCommandCount(@NotNull KeyStroke key, @NotNull CommandState editorState) { // See `:help N<Del>` return (editorState.getMode() == CommandState.Mode.COMMAND || editorState.getMode() == CommandState.Mode.VISUAL) && state == State.NEW_COMMAND && editorState.getCurrentArgumentType() != Argument.Type.CHARACTER && editorState.getCurrentArgumentType() != Argument.Type.DIGRAPH && key.getKeyCode() == KeyEvent.VK_DELETE && editorState.getCount() != 0; } private boolean isEditorReset(@NotNull KeyStroke key, @NotNull CommandState editorState) { return (editorState.getMode() == CommandState.Mode.COMMAND) && StringHelper.isCloseKeyStroke(key); } private void handleCharArgument(@NotNull KeyStroke key, char chKey) { // We are expecting a character argument - is this a regular character the user typed? // Some special keys can be handled as character arguments - let's check for them here. if (chKey == 0) { switch (key.getKeyCode()) { case KeyEvent.VK_TAB: chKey = '\t'; break; case KeyEvent.VK_ENTER: chKey = '\n'; break; } } if (chKey != 0) { // Create the character argument, add it to the current command, and signal we are ready to process // the command Argument arg = new Argument(chKey); Command cmd = currentCmd.peek(); cmd.setArgument(arg); state = State.READY; } else { // Oops - this isn't a valid character argument state = State.BAD_COMMAND; } } private boolean isCommandCount(char chKey, @NotNull CommandState editorState) { return (editorState.getMode() == CommandState.Mode.COMMAND || editorState.getMode() == CommandState.Mode.VISUAL) && state == State.NEW_COMMAND && editorState.getCurrentArgumentType() != Argument.Type.CHARACTER && editorState.getCurrentArgumentType() != Argument.Type.DIGRAPH && Character.isDigit(chKey) && (editorState.getCount() != 0 || chKey != '0'); } private boolean handleDigraph(@NotNull Editor editor, @NotNull KeyStroke key, @NotNull DataContext context, @NotNull CommandState editorState) { // Support starting a digraph/literal sequence if the operator accepts one as an argument, e.g. 'r' or 'f'. // Normally, we start the sequence (in Insert or CmdLine mode) through a VimAction that can be mapped. Our // VimActions don't work as arguments for operators, so we have to special case here. Helpfully, Vim appears to // hardcode the shortcuts, and doesn't support mapping, so everything works nicely. if (editorState.getCurrentArgumentType() == Argument.Type.DIGRAPH) { if (DigraphSequence.isDigraphStart(key)) { editorState.startDigraphSequence(); return true; } if (DigraphSequence.isLiteralStart(key)) { editorState.startLiteralSequence(); return true; } } DigraphResult res = editorState.processDigraphKey(key, editor); switch (res.getResult()) { case DigraphResult.RES_HANDLED: case DigraphResult.RES_BAD: return true; case DigraphResult.RES_DONE: if (editorState.getCurrentArgumentType() == Argument.Type.DIGRAPH) { editorState.setCurrentArgumentType(Argument.Type.CHARACTER); } final KeyStroke stroke = res.getStroke(); if (stroke == null) { return false; } handleKey(editor, stroke, context); return true; case DigraphResult.RES_UNHANDLED: if (editorState.getCurrentArgumentType() == Argument.Type.DIGRAPH) { editorState.setCurrentArgumentType(Argument.Type.CHARACTER); handleKey(editor, key, context); return true; } return false; } return false; } private void executeCommand(@NotNull Editor editor, @NotNull KeyStroke key, @NotNull DataContext context, @NotNull CommandState editorState) { // Let's go through the command stack and merge it all into one command. At this time there should never // be more than two commands on the stack - one is the actual command and the other would be a motion // command argument needed by the first command Command cmd = currentCmd.pop(); while (currentCmd.size() > 0) { Command top = currentCmd.pop(); top.setArgument(new Argument(cmd)); cmd = top; } // If we have a command and a motion command argument, both could possibly have their own counts. We // need to adjust the counts so the motion gets the product of both counts and the count associated with // the command gets reset. Example 3c2w (change 2 words, three times) becomes c6w (change 6 words) final Argument arg = cmd.getArgument(); if (arg != null && arg.getType() == Argument.Type.MOTION) { final Command mot = arg.getMotion(); // If no count was entered for either command then nothing changes. If either had a count then // the motion gets the product of both. int cnt = cmd.getRawCount() == 0 && mot.getRawCount() == 0 ? 0 : cmd.getCount() * mot.getCount(); mot.setCount(cnt); cmd.setCount(0); } // If we were in "operator pending" mode, reset back to normal mode. if (editorState.getMappingMode() == MappingMode.OP_PENDING) { editorState.popState(); } // Save off the command we are about to execute editorState.setCommand(cmd); Project project = editor.getProject(); final Command.Type type = cmd.getType(); if (type.isWrite() && !editor.getDocument().isWritable()) { VimPlugin.indicateError(); reset(editor); } if (!cmd.getFlags().contains(CommandFlags.FLAG_TYPEAHEAD_SELF_MANAGE)) { IdeEventQueue.getInstance().flushDelayedKeyEvents(); } if (ApplicationManager.getApplication().isDispatchThread()) { Runnable action = new ActionRunner(editor, context, cmd, key); EditorActionHandlerBase cmdAction = cmd.getAction(); String name = cmdAction.getId(); if (type.isWrite()) { RunnableHelper.runWriteCommand(project, action, name, action); } else if (type.isRead()) { RunnableHelper.runReadCommand(project, action, name, action); } else { CommandProcessor.getInstance().executeCommand(project, action, name, action); } } } private void handleCommandNode(Editor editor, DataContext context, KeyStroke key, @NotNull CommandNode node, CommandState editorState) { // The user entered a valid command. Create the command and add it to the stack final EditorActionHandlerBase myAction = node.getActionHolder().getAction(); Command cmd = new Command(editorState.getCount(), myAction, myAction.getType(), myAction.getFlags(), editorState.getKeys()); currentCmd.push(cmd); if (editorState.getCurrentArgumentType() != null && !checkArgumentCompatibility(node, editorState)) return; if (myAction.getArgumentType() == null || stopMacroRecord(node, editorState)) { state = State.READY; } else { editorState.setCurrentArgumentType(node.getActionHolder().getAction().getArgumentType()); startWaitingForArgument(editor, context, key.getKeyChar(), editorState.getCurrentArgumentType(), editorState); partialReset(editor); } // TODO In the name of God, get rid of EX_STRING, FLAG_COMPLETE_EX and all the related staff if (editorState.getCurrentArgumentType() == Argument.Type.EX_STRING && myAction.getFlags().contains(CommandFlags.FLAG_COMPLETE_EX)) { EditorActionHandlerBase action; if (VimPlugin.getProcess().isForwardSearch()) { action = new SearchEntryFwdAction(); } else { action = new SearchEntryRevAction(); } String text = VimPlugin.getProcess().endSearchCommand(editor); currentCmd.pop(); Argument arg = new Argument(text); cmd = new Command(editorState.getCount(), action, action.getType(), action.getFlags(), editorState.getKeys()); cmd.setArgument(arg); currentCmd.push(cmd); CommandState.getInstance(editor).popState(); } } private boolean stopMacroRecord(CommandNode node, @NotNull CommandState editorState) { return editorState.isRecording() && node.getActionHolder().getAction() instanceof ToggleRecordingAction; } private void startWaitingForArgument(Editor editor, DataContext context, char key, @NotNull Argument.Type argument, CommandState editorState) { switch (argument) { case CHARACTER: case DIGRAPH: state = State.CHAR_OR_DIGRAPH; break; case MOTION: if (CommandState.getInstance(editor).isDotRepeatInProgress() && VimRepeater.Extension.INSTANCE.getArgumentCaptured() != null) { currentCmd.peek().setArgument(VimRepeater.Extension.INSTANCE.getArgumentCaptured()); state = State.READY; } editorState.pushState(editorState.getMode(), editorState.getSubMode(), MappingMode.OP_PENDING); break; case EX_STRING: VimPlugin.getProcess().startSearchCommand(editor, context, editorState.getCount(), key); state = State.NEW_COMMAND; editorState.pushState(CommandState.Mode.CMD_LINE, CommandState.SubMode.NONE, MappingMode.CMD_LINE); currentCmd.pop(); } } private boolean checkArgumentCompatibility(@NotNull CommandNode node, @NotNull CommandState editorState) { if (editorState.getCurrentArgumentType() == Argument.Type.MOTION && node.getActionHolder().getAction().getType() != Command.Type.MOTION) { state = State.BAD_COMMAND; return false; } return true; } /** * Execute an action by name * * @param name The name of the action to execute * @param context The context to run it in */ public static boolean executeAction(@NotNull String name, @NotNull DataContext context) { ActionManager aMgr = ActionManager.getInstance(); AnAction action = aMgr.getAction(name); return action != null && executeAction(action, context); } /** * Partially resets the state of this handler. Resets the command count, clears the key list, resets the key tree * node to the root for the current mode we are in. * * @param editor The editor to reset. */ public void partialReset(@Nullable Editor editor) { CommandState editorState = CommandState.getInstance(editor); editorState.setCount(0); editorState.stopMappingTimer(); editorState.getMappingKeys().clear(); editorState.getKeys().clear(); editorState.setCurrentNode(VimPlugin.getKey().getKeyRoot(editorState.getMappingMode())); } /** * Resets the state of this handler. Does a partial reset then resets the mode, the command, and the argument * * @param editor The editor to reset. */ public void reset(@Nullable Editor editor) { partialReset(editor); state = State.NEW_COMMAND; currentCmd.clear(); CommandState editorState = CommandState.getInstance(editor); editorState.setCurrentArgumentType(null); } /** * Completely resets the state of this handler. Resets the command mode to normal, resets, and clears the selected * register. * * @param editor The editor to reset. */ public void fullReset(@Nullable Editor editor) { VimPlugin.clearError(); CommandState.getInstance(editor).reset(); reset(editor); VimPlugin.getRegister().resetRegister(); if (editor != null) { VisualGroupKt.updateCaretState(editor); editor.getSelectionModel().removeSelection(); } } // This method is copied from com.intellij.openapi.editor.actionSystem.EditorAction.getProjectAwareDataContext @NotNull private static DataContext getProjectAwareDataContext(@NotNull final Editor editor, @NotNull final DataContext original) { if (PROJECT.getData(original) == editor.getProject()) { return new DialogAwareDataContext(original); } return dataId -> { if (PROJECT.is(dataId)) { final Project project = editor.getProject(); if (project != null) { return project; } } return original.getData(dataId); }; } // This class is copied from com.intellij.openapi.editor.actionSystem.DialogAwareDataContext.DialogAwareDataContext private final static class DialogAwareDataContext implements DataContext { private static final DataKey[] keys = {PROJECT, PROJECT_FILE_DIRECTORY, EDITOR, VIRTUAL_FILE, PSI_FILE}; private final Map<String, Object> values = new HashMap<>(); DialogAwareDataContext(DataContext context) { for (DataKey key : keys) { values.put(key.getName(), key.getData(context)); } } @Nullable @Override public Object getData(@NotNull @NonNls String dataId) { if (values.containsKey(dataId)) { return values.get(dataId); } final Editor editor = (Editor)values.get(EDITOR.getName()); if (editor != null) { return DataManager.getInstance().getDataContext(editor.getContentComponent()).getData(dataId); } return null; } } /** * This was used as an experiment to execute actions as a runnable. */ static class ActionRunner implements Runnable { @Contract(pure = true) ActionRunner(Editor editor, DataContext context, Command cmd, KeyStroke key) { this.editor = editor; this.context = context; this.cmd = cmd; this.key = key; } @Override public void run() { CommandState editorState = CommandState.getInstance(editor); boolean wasRecording = editorState.isRecording(); KeyHandler.getInstance().state = State.NEW_COMMAND; executeVimAction(editor, cmd.getAction(), context); if (editorState.getMode() == CommandState.Mode.INSERT || editorState.getMode() == CommandState.Mode.REPLACE) { VimPlugin.getChange().processCommand(editor, cmd); } // Now the command has been executed let's clean up a few things. // By default, the "empty" register is used by all commands, so we want to reset whatever the last register // selected by the user was to the empty register - unless we just executed the "select register" command. if (cmd.getType() != Command.Type.SELECT_REGISTER) { VimPlugin.getRegister().resetRegister(); } // If, at this point, we are not in insert, replace, or visual modes, we need to restore the previous // mode we were in. This handles commands in those modes that temporarily allow us to execute normal // mode commands. An exception is if this command should leave us in the temporary mode such as // "select register" if (editorState.getSubMode() == CommandState.SubMode.SINGLE_COMMAND && (!cmd.getFlags().contains(CommandFlags.FLAG_EXPECT_MORE))) { editorState.popState(); } KeyHandler.getInstance().reset(editor); if (wasRecording && editorState.isRecording()) { VimPlugin.getRegister().recordKeyStroke(key); } } private final Editor editor; private final DataContext context; private final Command cmd; private final KeyStroke key; } private enum State { /** Awaiting a new command */ NEW_COMMAND, // TODO: This should be probably processed in some better way /** Awaiting char or digraph input. In this mode mappings doesn't work (even for <C-K>) */ CHAR_OR_DIGRAPH, READY, BAD_COMMAND } private TypedActionHandler origHandler; private static KeyHandler instance; // TODO: All of this state needs to be per-editor private State state = State.NEW_COMMAND; @NotNull private final Stack<Command> currentCmd = new Stack<>(); }
package com.opera.core.systems; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import org.openqa.selenium.Platform; /** * @author stuartk * This class tries to find the paths to Opera and Opera Launcher on any system */ public class OperaPaths { /** * This method will try and find Opera on any system. It takes the following * steps: * 1. Check the environment variable "OPERA_PATH". If it exists, and the * file it points to exists, then return * 2. (Unix) Call `which opera` to find the location * 3. Check if Opera exists at the default location on the respective OS * 4. Give up and return null * @return The path to Opera, or null */ public String operaPath() { String path = null; if ((path = checkPath(System.getenv("OPERA_PATH"))) != null) return path; Platform platform = Platform.getCurrent(); // TODO find if Mac supports `which` if (platform.is(Platform.LINUX) || platform.is(Platform.UNIX)) { if ((path = checkPath(execProg("which opera"))) != null) return path; } if (platform.is(Platform.LINUX) || platform.is(Platform.UNIX)) { if ((path = checkPath("/usr/bin/opera")) != null) return path; } else if (platform.is(Platform.WINDOWS)) { String progfiles = System.getenv("PROGRAMFILES"); if (progfiles == null) progfiles = "\\Program Files"; if ((path = checkPath(progfiles + "\\Opera\\opera.exe")) != null) return path; } else if (platform.is(Platform.MAC)) { if ((path = checkPath("/Applications/Opera.app/Contents/MacOS/Opera")) != null) return path; } return null; } /** * This method will try and find Opera Launcher on any system. Currently it * just looks at the OPERA_LAUNCHER environment variable. * TODO: Do we want to package the launchers in the jar? If so this can * find them there. * @return The path to Opera Launcher, or null */ public String launcherPath() { String path = null; if ((path = checkPath(System.getenv("OPERA_LAUNCHER"))) != null) return path; return null; } /** * Check that the given path is not null, and exists. * @param path The path to check. * @return null if the path is null, or does not exist. Otherwise it returns * the given path. */ private String checkPath(String path) { if (path == null) return null; File file = new File(path); if (file.exists()) return path; return null; } private String execProg(String cmd) { String output = ""; try { Process process = Runtime.getRuntime().exec(cmd); BufferedReader out= new BufferedReader(new InputStreamReader(process.getInputStream())); String line = null; while ((line = out.readLine()) != null) { output += line; } process.waitFor(); } catch (Exception e) { return null; } return output; } }
package org.jasig.portal; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.sql.Connection; import java.sql.Driver; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jasig.portal.properties.PropertiesManager; import org.jasig.portal.rdbm.DatabaseMetaDataImpl; import org.jasig.portal.rdbm.IDatabaseMetadata; import org.jasig.portal.rdbm.pool.IPooledDataSourceFactory; import org.jasig.portal.rdbm.pool.PooledDataSourceFactoryFactory; import org.jasig.portal.utils.MovingAverage; import org.jasig.portal.utils.MovingAverageSample; import org.springframework.dao.DataAccessResourceFailureException; import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicInteger; /** * Provides relational database access and helper methods. * A static routine determines if the database/driver supports * prepared statements and/or outer joins. * * <p>This class provides database access as a service. Via the class, uPortal * code can obtain a connection to the core uPortal database as well as to other * databases available via JNDI. (Doing that JNDI lookup directly allows your * code to avoid dependence upon this class.) This class provides * traditional getConnection() methods as well as static covers for getting a * reference to the backing DataSource.</p> * * <p>This class also provides helper methods for manipulating connections. * Mostof the methods are wrappers around methods on the underlying Connection * that handle (log and swallow) the SQLExceptions that the underlying methods * declare to be thrown (these helpers also catch * and log RuntimeExceptions encountered). They provide an alternative to trying * and catching those methods using the JDBC APIs directly.</p> * * @author Ken Weiner, kweiner@unicon.net * @author George Lindholm, george.lindholm@ubc.ca * @author Eric Dalquist <a href="mailto:edalquist@unicon.net">edalquist@unicon.net</a> * @author Susan Bramhall <a href="mailto:susan.bramhall@yale.edu">susan.bramhall@yale.edu</a> * @version $Revision$ $Date$ */ public class RDBMServices { public static final String PORTAL_DB = PropertiesManager.getProperty("org.jasig.portal.RDBMServices.PortalDatasourceJndiName", "PortalDb"); // JNDI name for portal database public static final String DEFAULT_DATABASE = "DEFAULT_DATABASE"; private static boolean getDatasourceFromJndi = PropertiesManager.getPropertyAsBoolean("org.jasig.portal.RDBMServices.getDatasourceFromJndi", true); private static final Log LOG = LogFactory.getLog(RDBMServices.class); //DBFlag constants private static final String FLAG_TRUE = "Y"; private static final String FLAG_TRUE_OTHER = "T"; private static final String FLAG_FALSE = "N"; /** Specifies how long to wait before trying to look a JNDI data source that previously failed */ private static final int JNDI_RETRY_TIME = PropertiesManager.getPropertyAsInt("org.jasig.portal.RDBMServices.jndiRetryDelay", 30000); // JNDI retry delay; private static Map namedDataSources = Collections.synchronizedMap(new HashMap()); private static Map namedDbServerFailures = Collections.synchronizedMap(new HashMap()); /* info legacy utilities */ private static String jdbcUrl; private static String jdbcUser; private static String jdbcDriver; private static IDatabaseMetadata dbMetaData = null; // Metric counters private static final MovingAverage databaseTimes = new MovingAverage(); public static MovingAverageSample lastDatabase = new MovingAverageSample(); private static AtomicInteger activeConnections = new AtomicInteger(); private static int maxConnections = 0; /** * Gets the default DataSource. If no server is found * a runtime exception will be thrown. This method will never return null. * @return the core uPortal DataSource * @throws RuntimeException on failure */ public static DataSource getDataSource() { return getDataSource(PORTAL_DB); } /** * Gets a named DataSource from JNDI, with special handling for the PORTAL_DB * datasource. Successful lookups * are cached and not done again. Lookup failure is remembered and blocks retry * for a * number of milliseconds specified by {@link #JNDI_RETRY_TIME} to reduce * JNDI overhead and log spam. * * There are two ways in which we handle the core uPortal DataSource * specially. * * We determine and remember metadata in an DbMetaData object for the core * uPortal DataSource. We do not compute this DbMetaData for any other * DataSource. * * We fall back on using rdbm.properties to construct our core uPortal * DataSource in the case where we cannot find it from JNDI. If the portal * property org.jasig.portal.RDBMServices.getDatasourceFromJNDI is true, * we first * first try to get the connection by looking in the * JNDI context for the name defined by the portal property * org.jasig.portal.RDBMServices.PortalDatasourceJndiName . * * If we were not configured to check JNDI or we didn't find it in JNDI having * checked, we then fall back on rdbm.properties. * * @param name The name of the DataSource to get. * @return A named DataSource or <code>null</code> if one cannot be found. */ public static DataSource getDataSource(String name) { final String PROP_FILE = "/properties/rdbm.properties"; if (DEFAULT_DATABASE.equals(name)) { name = PORTAL_DB; } DataSource ds = (DataSource)namedDataSources.get(name); // if already have a dtasource just return it if (ds!=null) return ds; // For non default database cache the datasource and return it if (!PORTAL_DB.equals(name)) { ds = getJndiDataSource(name); namedDataSources.put(name,ds); // For non default database return whatever we have (could be null) return ds; } // portal database is special - create metadata object too. if (getDatasourceFromJndi) { ds = getJndiDataSource(name); if (ds != null) { if (LOG.isInfoEnabled()) LOG.info("Creating DataSource instance for " + name); dbMetaData = new DatabaseMetaDataImpl(ds); namedDataSources.put(name, ds); return ds; } } // get here if not getDatasourceFromJndi OR jndi lookup returned null // try to get datasource via properties try { final InputStream jdbcPropStream = RDBMServices.class.getResourceAsStream(PROP_FILE); try { final Properties jdbpProperties = new Properties(); jdbpProperties.load(jdbcPropStream); final IPooledDataSourceFactory pdsf = PooledDataSourceFactoryFactory.getPooledDataSourceFactory(); final String driverClass = jdbpProperties.getProperty("jdbcDriver"); final String username = jdbpProperties.getProperty("jdbcUser"); final String password = jdbpProperties.getProperty("jdbcPassword"); final String url = jdbpProperties.getProperty("jdbcUrl"); boolean usePool = true; if (jdbpProperties.getProperty("jdbcUsePool")!=null) usePool = Boolean.valueOf(jdbpProperties.getProperty("jdbcUsePool")).booleanValue(); if (usePool) { //Try using a pooled DataSource try { final boolean poolPreparedStatements = Boolean.valueOf(jdbpProperties.getProperty("poolPreparedStatements")).booleanValue(); ds = pdsf.createPooledDataSource(driverClass, username, password, url, poolPreparedStatements); if (LOG.isInfoEnabled()) LOG.info("Creating DataSource instance for pooled JDBC"); namedDataSources.put(PORTAL_DB,ds); jdbcUrl = url; jdbcUser = username; jdbcDriver = driverClass; dbMetaData = new DatabaseMetaDataImpl(ds); } catch (Exception e) { LOG.error("Error using pooled JDBC data source.", e); } } if (ds == null && driverClass != null) { //Pooled DataSource isn't being used or failed during creation try { final Driver d = (Driver)Class.forName(driverClass).newInstance(); ds = new GenericDataSource(d, url, username, password); if (LOG.isInfoEnabled()) LOG.info("Creating DataSource for JDBC native"); namedDataSources.put(PORTAL_DB,ds); jdbcUrl = url; jdbcUser = username; jdbcDriver = driverClass; dbMetaData = new DatabaseMetaDataImpl(ds); } catch (Exception e) { LOG.error("JDBC Driver Creation Failed. (" + driverClass + ")", e); } } } finally { jdbcPropStream.close(); } } catch (IOException ioe) { LOG.error("An error occured while reading " + PROP_FILE, ioe); } // if we failed to find a datasource then throw a runtime exception if (ds == null) { throw new RuntimeException("No JDBC DataSource or JNDI DataSource avalable."); } return ds; } /** * Does the JNDI lookup and returns datasource * @param name * @return */ private static DataSource getJndiDataSource(String name) { final Long failTime = (Long)namedDbServerFailures.get(name); DataSource ds = null; if (failTime == null || (failTime.longValue() + JNDI_RETRY_TIME) <= System.currentTimeMillis()) { if (failTime != null) { namedDbServerFailures.remove(name); } try { final Context initCtx = new InitialContext(); final Context envCtx = (Context)initCtx.lookup("java:comp/env"); ds = (DataSource)envCtx.lookup("jdbc/" + name); } catch (Throwable t) { //Cache the failure to decrease lookup attempts and reduce log spam. namedDbServerFailures.put(name, new Long(System.currentTimeMillis())); if (LOG.isWarnEnabled()) LOG.warn("Error getting DataSource named (" + name + ") from JNDI.", t); } } else { if (LOG.isDebugEnabled()) { final long waitTime = (failTime.longValue() + JNDI_RETRY_TIME) - System.currentTimeMillis(); LOG.debug("Skipping lookup on failed JNDI lookup for name (" + name + ") for approximately " + waitTime + " more milliseconds."); } } return ds; } /** * Return the current number of active connections * @return int */ public static int getActiveConnectionCount() { return activeConnections.intValue(); } /** * Return the maximum number of connections * @return int */ public static int getMaxConnectionCount() { return maxConnections; } /** * Gets a database connection to the portal database. * If datasource not available a runtime exception is thrown * @return a database Connection object * @throws DataAccessException if unable to return a connection */ public static Connection getConnection() { return getConnection(PORTAL_DB); } /** * Returns a connection produced by a DataSource found in the * JNDI context. The DataSource should be configured and * loaded into JNDI by the J2EE container or may be the portal * default database. * * @param dbName the database name which will be retrieved from * the JNDI context relative to "jdbc/" * @return a database Connection object or <code>null</code> if no Connection */ public static Connection getConnection(String dbName) { if (DEFAULT_DATABASE.equals(dbName)){ dbName = PORTAL_DB; } DataSource ds = (DataSource) namedDataSources.get(dbName); if (ds==null) { ds = getDataSource(dbName); } if (ds != null) { try { final long start = System.currentTimeMillis(); final Connection c = ds.getConnection(); lastDatabase = databaseTimes.add(System.currentTimeMillis() - start); // metric final int current = activeConnections.incrementAndGet(); if (current > maxConnections) { maxConnections = current; } return c; } catch (SQLException e) { throw new DataAccessResourceFailureException ("RDBMServices sql error trying to get connection to "+dbName,e); } } // datasource is still null so give up throw new DataAccessResourceFailureException("RDBMServices fatally misconfigured such that getDataSource() returned null."); } /** * Releases database connection. * Unlike the underlying connection.close(), this method does not throw * SQLException or any other exception. It will fail silently from the * perspective of calling code, logging errors using Commons Logging. * @param con a database Connection object */ public static void releaseConnection(final Connection con) { try { int active = activeConnections.decrementAndGet(); con.close(); } catch (Exception e) { if (LOG.isWarnEnabled()) LOG.warn("Error closing Connection: " + con, e); } } /** * Close a ResultSet * @param rs a database ResultSet object */ public static void closeResultSet(final ResultSet rs) { try { rs.close(); } catch (Exception e) { if (LOG.isWarnEnabled()) LOG.warn("Error closing ResultSet: " + rs, e); } } /** * Close a Statement * @param st a database Statement object */ public static void closeStatement(final Statement st) { try { st.close(); } catch (Exception e) { if (LOG.isWarnEnabled()) LOG.warn("Error closing Statement: " + st, e); } } /** * Close a PreparedStatement. Simply delegates the call to * {@link #closeStatement(Statement)} * @param pst a database PreparedStatement object * @deprecated Use {@link #closeStatement(Statement)}. */ public static void closePreparedStatement(final java.sql.PreparedStatement pst) { closeStatement(pst); } /** * Commit pending transactions. * Unlike the underlying commit(), this method does not throw SQLException or * any other exception. It will fail silently from the perspective of calling code, * logging any errors using Commons Logging. * @param connection */ static final public void commit(final Connection connection) { try { connection.commit(); } catch (Exception e) { if (LOG.isWarnEnabled()) LOG.warn("Error committing Connection: " + connection, e); } } /** * Set auto commit state for the connection. * Unlike the underlying connection.setAutoCommit(), this method does not * throw SQLException or any other Exception. It fails silently from the * perspective of calling code, logging any errors encountered using * Commons Logging. * @param connection * @param autocommit */ public static final void setAutoCommit(final Connection connection, boolean autocommit) { try { connection.setAutoCommit(autocommit); } catch (Exception e) { if (LOG.isWarnEnabled()) LOG.warn("Error committing Connection: " + connection + " to: " + autocommit, e); } } /** * rollback unwanted changes to the database * @param connection */ public static final void rollback(final Connection connection) throws SQLException { try { connection.rollback(); } catch (Exception e) { if (LOG.isWarnEnabled()) LOG.warn("Error rolling back Connection: " + connection, e); } } /** * Returns the name of the JDBC driver being used for the default * uPortal database connections. * * @return the name of the JDBC Driver. */ public static String getJdbcDriver () { return jdbcDriver; } /** * Gets the JDBC URL of the default uPortal database connections. * */ public static String getJdbcUrl () { return jdbcUrl; } /** * Get the username under which we are connecting for the default uPortal * database connections. */ public static String getJdbcUser () { return jdbcUser; } /** * Return DB format of a boolean. "Y" for true and "N" for false. * @param flag true or false * @return either "Y" or "N" */ public static final String dbFlag(final boolean flag) { if (flag) return FLAG_TRUE; else return FLAG_FALSE; } /** * Return boolean value of DB flag, "Y" or "N". * @param flag either "Y" or "N" * @return boolean true or false */ public static final boolean dbFlag(final String flag) { return flag != null && (FLAG_TRUE.equalsIgnoreCase(flag) || FLAG_TRUE_OTHER.equalsIgnoreCase(flag)); } /** * Make a string SQL safe * @param sql * @return SQL safe string */ public static final String sqlEscape(final String sql) { if (sql == null) { return ""; } else { int primePos = sql.indexOf("'"); if (primePos == -1) { return sql; } else { final StringBuffer sb = new StringBuffer(sql.length() + 4); int startPos = 0; do { sb.append(sql.substring(startPos, primePos + 1)); sb.append("'"); startPos = primePos + 1; primePos = sql.indexOf("'", startPos); } while (primePos != -1); sb.append(sql.substring(startPos)); return sb.toString(); } } } /** * Get metadata about the default DataSource. * @return metadata about the default DataSource. */ public static IDatabaseMetadata getDbMetaData() { if (dbMetaData==null) { // if metadata not yet populated, call getDataSource(), which // has side effect of populating dbMetaData. getDataSource(); } return dbMetaData; } /** * Inner class implementation of DataSource. We currently construct an instance * of this class from the properties defined in rdbm.properties when we are using * rdbm.properties to define our core uPortal DataSource. * @author Eric Dalquist <a href="mailto:edalquist@unicon.net">edalquist@unicon.net</a> */ public static class GenericDataSource implements DataSource { final private Driver driverRef; final private String userName; final private String password; final private String jdbcUrl; final private Properties jdbcProperties = new Properties(); private PrintWriter log = null; /** * Create a new {@link GenericDataSource} with the wraps the specified * {@link Driver}. * * @param d The {@link Driver} to wrap. */ public GenericDataSource(final Driver d, final String url, final String user, final String pass) { String argErr = ""; if (d == null) { argErr += "Driver cannot be null. "; } if (url == null) { argErr += "url cannot be null. "; } if (user == null) { argErr += "user cannot be null. "; } if (pass == null) { argErr += "pass cannot be null. "; } if (!argErr.equals("")) { throw new IllegalArgumentException(argErr); } this.driverRef = d; this.jdbcUrl = url; this.userName = user; this.password = pass; this.jdbcProperties.put("user", this.userName); this.jdbcProperties.put("password", this.password); } /** * @see javax.sql.DataSource#getLoginTimeout() */ public int getLoginTimeout() throws SQLException { return 0; } /** * @see javax.sql.DataSource#setLoginTimeout(int) */ public void setLoginTimeout(final int timeout) throws SQLException { //NOOP our timeout is always 0 } /** * @see javax.sql.DataSource#getLogWriter() */ public PrintWriter getLogWriter() throws SQLException { return this.log; } /** * @see javax.sql.DataSource#setLogWriter(java.io.PrintWriter) */ public void setLogWriter(final PrintWriter out) throws SQLException { this.log = out; } /** * @see javax.sql.DataSource#getConnection() */ public Connection getConnection() throws SQLException { return this.getConnection(this.userName, this.password); } /** * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String) */ public Connection getConnection(final String user, final String pass) throws SQLException { final Properties tempProperties = new Properties(); tempProperties.putAll(this.jdbcProperties); tempProperties.put("user", user); tempProperties.put("password", pass); return this.driverRef.connect(this.jdbcUrl, tempProperties); } /** * This method was introduced in Java SE 6 as part of the java.sql.Wrapper * interface that javax.sql.DataSource was changed to extend from. * * Returns true if this either implements the interface argument * or is directly or indirectly a wrapper for an object that does. * Returns false otherwise. If this implements the interface then * return true, else if this is a wrapper then return the result * of recursively calling <code>isWrapperFor</code> on the wrapped * object. If this does not implement the interface and is not a * wrapper, return false. This method should be implemented as a * low-cost operation compared to <code>unwrap</code> so that * callers can use this method to avoid expensive <code>unwrap</code> * calls that may fail. If this method returns true then calling * <code>unwrap</code> with the same argument should succeed. * * @param iface a Class defining an interface. * @return true if this implements the interface or directly or * indirectly wraps an object that does. * @throws java.sql.SQLException if an error occurs while determining * whether this is a wrapper for an object with the given interface. * @see java.sql.Wrapper#isWrapperFor(java.lang.Class) */ public boolean isWrapperFor(Class<?> iface) throws SQLException { return (iface != null && iface.isAssignableFrom(this.getClass())); } /** * This method was introduced in Java SE 6 as part of the java.sql.Wrapper * interface that javax.sql.DataSource was changed to extend from. * * If the receiving object implements the interface passed in, then * the receiving object or a wrapper for the receiving object should * be returned. * * @param iface A Class defining an interface that the result must * implement * @return an object that implements the interface. May be a proxy for * the actual implementing object. * @throws java.sql.SQLException if a class is not a wrapper for another * class and does not implement the interface passed. * @see java.sql.Wrapper#unwrap(java.lang.Class) */ public <T> T unwrap(Class<T> iface) throws SQLException { if (isWrapperFor(iface)) { return iface.cast(this); } throw new SQLException("org.jasig.portal.RDBMServices.GenericDataSource is not a Wrapper for " + iface.toString()); } } /** * Wrapper for/Emulator of PreparedStatement class * @deprecated Instead of this class a wrapper around the DataSource, Connection and Prepared statement should be done in {@link DatabaseMetaDataImpl} */ public static final class PreparedStatement { private String query; private String activeQuery; private java.sql.PreparedStatement pstmt; private Statement stmt; private int lastIndex; public PreparedStatement(Connection con, String query) throws SQLException { this.query = query; activeQuery = this.query; if (dbMetaData.supportsPreparedStatements()) { pstmt = con.prepareStatement(query); } else { stmt = con.createStatement(); } } public void clearParameters() throws SQLException { if (dbMetaData.supportsPreparedStatements()) { pstmt.clearParameters(); } else { lastIndex = 0; activeQuery = query; } } public void setDate(int index, java.sql.Date value) throws SQLException { if (dbMetaData.supportsPreparedStatements()) { pstmt.setDate(index, value); } else { if (index != lastIndex + 1) { throw new SQLException("Out of order index"); } else { int pos = activeQuery.indexOf("?"); if (pos == -1) { throw new SQLException("Missing '?'"); } activeQuery = activeQuery.substring(0, pos) + dbMetaData.sqlTimeStamp(value) + activeQuery.substring(pos + 1); lastIndex = index; } } } public void setInt(int index, int value) throws SQLException { if (dbMetaData.supportsPreparedStatements()) { pstmt.setInt(index, value); } else { if (index != lastIndex + 1) { throw new SQLException("Out of order index"); } else { int pos = activeQuery.indexOf("?"); if (pos == -1) { throw new SQLException("Missing '?'"); } activeQuery = activeQuery.substring(0, pos) + value + activeQuery.substring(pos + 1); lastIndex = index; } } } public void setNull(int index, int sqlType) throws SQLException { if (dbMetaData.supportsPreparedStatements()) { pstmt.setNull(index, sqlType); } else { if (index != lastIndex + 1) { throw new SQLException("Out of order index"); } else { int pos = activeQuery.indexOf("?"); if (pos == -1) { throw new SQLException("Missing '?'"); } activeQuery = activeQuery.substring(0, pos) + "NULL" + activeQuery.substring(pos + 1); lastIndex = index; } } } public void setString(int index, String value) throws SQLException { if (value == null || value.length() == 0) { setNull(index, java.sql.Types.VARCHAR); } else { if (dbMetaData.supportsPreparedStatements()) { pstmt.setString(index, value); } else { if (index != lastIndex + 1) { throw new SQLException("Out of order index"); } else { int pos = activeQuery.indexOf("?"); if (pos == -1) { throw new SQLException("Missing '?'"); } activeQuery = activeQuery.substring(0, pos) + "'" + sqlEscape(value) + "'" + activeQuery.substring(pos + 1); lastIndex = index; } } } } public void setTimestamp(int index, java.sql.Timestamp value) throws SQLException { if (dbMetaData.supportsPreparedStatements()) { pstmt.setTimestamp(index, value); } else { if (index != lastIndex + 1) { throw new SQLException("Out of order index"); } else { int pos = activeQuery.indexOf("?"); if (pos == -1) { throw new SQLException("Missing '?'"); } activeQuery = activeQuery.substring(0, pos) + dbMetaData.sqlTimeStamp(value) + activeQuery.substring(pos + 1); lastIndex = index; } } } public ResultSet executeQuery() throws SQLException { if (dbMetaData.supportsPreparedStatements()) { return pstmt.executeQuery(); } else { return stmt.executeQuery(activeQuery); } } public int executeUpdate() throws SQLException { if (dbMetaData.supportsPreparedStatements()) { return pstmt.executeUpdate(); } else { return stmt.executeUpdate(activeQuery); } } public String toString() { if (dbMetaData.supportsPreparedStatements()) { return query; } else { return activeQuery; } } public void close() throws SQLException { if (dbMetaData.supportsPreparedStatements()) { pstmt.close(); } else { stmt.close(); } } } /** * @return Returns the getDatasourceFromJndi. */ public static boolean isGetDatasourceFromJndi() { return getDatasourceFromJndi; } /** * @param getDatasourceFromJndi The getDatasourceFromJndi to set. */ public static void setGetDatasourceFromJndi(boolean getDatasourceFromJndi) { RDBMServices.getDatasourceFromJndi = getDatasourceFromJndi; } }
package com.rapid.data; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.sql.SQLException; import javax.servlet.ServletContext; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import com.rapid.core.Application; import com.rapid.utils.JAXB.EncryptedXmlAdapter; // the details of a database connection (WebService is defined in its own class as its extendable) public class DatabaseConnection { // instance variables String _name, _driverClass, _connectionString, _connectionAdapterClass, _userName, _password; ConnectionAdapter _connectionAdapter; // properties public String getName() { return _name; } public void setName(String name) { _name = name; } public String getDriverClass() { return _driverClass; } public void setDriverClass(String driverClass) { _driverClass = driverClass; } public String getConnectionString() { return _connectionString; } public void setConnectionString(String connectionString) { _connectionString = connectionString; } public String getConnectionAdapterClass() { return _connectionAdapterClass; } public void setConnectionAdapterClass(String connectionAdapterClass) { _connectionAdapterClass = connectionAdapterClass; } public String getUserName() { return _userName; } public void setUserName(String userName) { _userName = userName; } @XmlJavaTypeAdapter( EncryptedXmlAdapter.class ) public String getPassword() { return _password; } public void setPassword(String password) { _password = password; } // constructors public DatabaseConnection() {}; public DatabaseConnection(ServletContext servletContext, Application application, String name, String driverClass, String connectionString, String connectionAdapterClass, String userName, String password) { _name = name; _driverClass = driverClass; _connectionString = connectionString; _connectionAdapterClass = connectionAdapterClass; _userName = userName; _password = password; } // instance methods // get the connection adapter, instantiating only if null as this is quite expensive public synchronized ConnectionAdapter getConnectionAdapter(ServletContext servletContext, Application application) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { // only if the connection adapter has not already been initialised if (_connectionAdapter == null) { // get our class Class classClass = Class.forName(_connectionAdapterClass); // initialise a constructor Constructor constructor = classClass.getConstructor(ServletContext.class, String.class, String.class, String.class, String.class); // get the connection string String connectionString = _connectionString; // if there is an app, insert the parameters to the connection string if (application != null) connectionString = application.insertParameters(servletContext, _connectionString); // initialise the class _connectionAdapter = (ConnectionAdapter) constructor.newInstance( servletContext, _driverClass, connectionString, _userName, _password) ; } return _connectionAdapter; } // set the connection adapter to null to for it to be re-initialised public synchronized void reset() throws SQLException { // close it first close(); // set it to null _connectionAdapter = null; } // set the connection adapter to null to for it to be re-initialised public synchronized void close() throws SQLException { if (_connectionAdapter != null) _connectionAdapter.close(); } }
package com.redpois0n.guiscrot; import java.awt.AWTException; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.GraphicsDevice; import java.awt.Image; import java.awt.Rectangle; import java.awt.Robot; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.event.MouseInputListener; import org.jnativehook.GlobalScreen; import org.jnativehook.mouse.NativeMouseEvent; import org.jnativehook.mouse.NativeMouseMotionListener; @SuppressWarnings("serial") public class CoverFrame extends JFrame implements MouseMotionListener, MouseInputListener, NativeMouseMotionListener { public static final float OPACITY = 0.5F; private Rectangle rect; private Image image; private int x; private int y; private int x2; private int y2; private boolean dragging; private int seed; private RepaintThread thread; public CoverFrame(Rectangle rect) { this(rect, null); } public CoverFrame(Rectangle rect, Image image) { this.rect = rect; this.image = image; GlobalScreen.addNativeMouseMotionListener(this); setUndecorated(true); setBounds(rect); setContentPane(new CoverPanel()); addMouseListener(this); addMouseMotionListener(this); if (image == null) { setOpacity(OPACITY); } thread = new RepaintThread(); thread.start(); } private class RepaintThread extends Thread { @Override public void run() { while (!interrupted()) { if (seed++ >= 20) { seed = 0; } repaint(); try { Thread.sleep(100L); } catch (Exception ex) { ex.printStackTrace(); } } } } private class CoverPanel extends JPanel { @Override public void paintComponent(Graphics g) { super.paintComponent(g); if (x > x2 && x2 != 0) { int temp = x; x = x2; x2 = temp; } if (y > y2 && y2 != 0) { int temp = y; y = y2; y2 = temp; } /** If nothing is selected, default to x and y**/ int tx = x2 == 0 ? x : x2; int ty = y2 == 0 ? y : y2; if (image != null) { /** Draw image over frame **/ g.drawImage(image, 0, 0, getWidth(), getHeight(), null); /** Set color to transparent black **/ g.setColor(new Color(0, 0, 0, 100)); /** Draw black transparent color over all areas that isn't being selected **/ g.fillRect(0, 0, x, getHeight()); g.fillRect(x, 0, getWidth(), y); g.fillRect(tx, y, getWidth(), getHeight()); g.fillRect(x, ty, tx - x, getHeight()); } else { g.setColor(Color.black); g.fillRect(0, 0, getWidth(), getHeight()); } g.setColor(Color.white); RendererUtils.drawMovingRect(x, 0, 1, getHeight(), g, seed); RendererUtils.drawMovingRect(0, y, getWidth(), 1, g, seed); g.setColor(Color.white); g.setFont(new Font("Arial", Font.BOLD, 16)); if (dragging) { g.drawString("X " + (x + rect.x) + " / Y " + (y + rect.y), x + 2, y - 4 - g.getFontMetrics().getHeight()); g.drawString("Width " + (x2 - x) + " / Height " + (y2 - y), x + 2, y - 2); } if (x2 != 0 && y2 != 0) { g.setColor(Color.red); g.drawRect(x, y, tx - x, ty - y); RendererUtils.drawMovingRect(x, y, tx - x, ty - y, g, seed); } } } @Override protected void finalize() { thread.interrupt(); } @Override public void nativeMouseDragged(NativeMouseEvent arg0) { x2 = arg0.getX() - rect.x; y2 = arg0.getY() - rect.y; repaint(); } @Override public void nativeMouseMoved(NativeMouseEvent arg0) { } @Override public void mouseDragged(MouseEvent arg0) { dragging = true; } @Override public void mouseMoved(MouseEvent arg0) { if (!dragging) { x = arg0.getX();// - rect.x; y = arg0.getY();// - rect.y; } repaint(); } @Override public void mouseClicked(MouseEvent arg0) { } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { dragging = true; repaint(); } @Override public void mouseReleased(MouseEvent arg0) { dragging = false; x2 = 0; y2 = 0; repaint(); } }
package com.unifi.ing.engine.entity; import java.util.ArrayList; import java.util.List; import org.lwjgl.input.Keyboard; import org.lwjgl.util.vector.Vector3f; import com.unifi.ing.engine.model.TexturedModel; import com.unifi.ing.engine.terrains.Terrain; import com.unifi.ing.engine.utils.DisplayManager; import com.unifi.ing.engine.utils.Maths; import com.unifi.ing.pattern.observer.Observable; import com.unifi.ing.pattern.observer.Observer; public class Rover extends Entity implements Observable{ private static final float RUN_SPEED = 20; private static final float TURN_SPEED = 160.0f;//160 private static final float GRAVITY = -20; private float currentSpeed = 0; private float currentTurnSpeed = 0; private float upwardsSpeed = 0; private float rotX = 1.60f; private float rotY = 1.60f; private float rotZ = 1.60f; List<Observer> observerEntity = null; public Rover(TexturedModel model, Vector3f position, float rotX, float rotY, float rotZ, float scale) { super(model, position, rotX, rotY, rotZ, scale); observerEntity = new ArrayList<>(); } public void move(Terrain terrain){ checkInputs(terrain); super.increaseRotation(0, currentTurnSpeed * DisplayManager.getFrameTimeSeconds(), 0); float distance = currentSpeed * DisplayManager.getFrameTimeSeconds(); float dx = (float) (distance * Math.sin(Math.toRadians(super.getRotY()))); float dz = (float) (distance * Math.cos(Math.toRadians(super.getRotY()))); super.increasePosition(dx, 0, dz); upwardsSpeed += GRAVITY * DisplayManager.getFrameTimeSeconds(); super.increasePosition(0, upwardsSpeed * DisplayManager.getFrameTimeSeconds() , 0); float terrainHeight = terrain.getHeightOfTerrain(super.getPosition().x, super.getPosition().z); if(super.getPosition().y < terrainHeight){ upwardsSpeed = 0; super.getPosition().y = terrainHeight; } notifyEntity(terrain); // super.setRotZ(calcRotZ()); // super.setRotX(calcRotX()); } private float calcRotZ(){ Cube cubeA = (Cube) observerEntity.get(1); Cube cubeB = (Cube) observerEntity.get(3); float a = Maths.mul(cubeA.getPosition(), cubeB.getPosition()); float b = Maths.len(cubeA.getPosition()) * Maths.len(cubeB.getPosition()); return (float) Math.acos(a/b); } private float calcRotX(){ Cube cubeA = (Cube) observerEntity.get(0); Cube cubeB = (Cube) observerEntity.get(2); float a = Maths.mul(cubeA.getPosition(), cubeB.getPosition()); float b = Maths.len(cubeA.getPosition()) * Maths.len(cubeB.getPosition()); return (float) Math.acos(a/b); } private void checkInputs(Terrain terrain){ if(Keyboard.isKeyDown(Keyboard.KEY_W)){ this.currentSpeed = +RUN_SPEED; }else if(Keyboard.isKeyDown(Keyboard.KEY_S)){ this.currentSpeed = -RUN_SPEED; }else{ this.currentSpeed = 0; } if(Keyboard.isKeyDown(Keyboard.KEY_D)){ this.currentTurnSpeed = -TURN_SPEED; }else if(Keyboard.isKeyDown(Keyboard.KEY_A)){ this.currentTurnSpeed = TURN_SPEED; }else{ this.currentTurnSpeed = 0; } if(Keyboard.isKeyDown(Keyboard.KEY_B)){ super.increaseRotation(rotX, 0, 0); } if(Keyboard.isKeyDown(Keyboard.KEY_N)){ super.increaseRotation(0, rotY, 0); } if(Keyboard.isKeyDown(Keyboard.KEY_M)){ super.increaseRotation(0, 0, rotZ); } if(Keyboard.isKeyDown(Keyboard.KEY_H)){ super.increaseRotation(-rotX, 0, 0); } if(Keyboard.isKeyDown(Keyboard.KEY_J)){ super.increaseRotation(0, -rotY, 0); } if(Keyboard.isKeyDown(Keyboard.KEY_K)){ super.increaseRotation(0, 0, -rotZ); } if(Keyboard.isKeyDown(Keyboard.KEY_R)){ this.setRotY(0); this.setRotX(0); this.setRotZ(0); this.setPosition(new Vector3f(600, 30, 550)); } } @Override public void notifyEntity(Terrain terrain) { for (Observer observer : observerEntity) { observer.update(this, terrain); } } public void addObserver(Observer observer){ observerEntity.add(observer); } }
package client; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import slimpleslickgame.Game; import util.Logger; /** * Contains events for all players currently in game. * * @author timdolck * */ public class GameStatsEvents { private ConcurrentMap<Byte, Queue<GameEvent>> events; private Game game; private byte localId = -1; public GameStatsEvents(Game game){ events = new ConcurrentHashMap<Byte, Queue<GameEvent>>(); this.game = game; } public GameEvent pop(byte id) { Queue<GameEvent> queue = events.get(id); if (queue == null) { throw new IllegalArgumentException("Id does not exist, id: " + id); } if(queue.isEmpty()){ return null; } return queue.poll(); } public void put(byte id, GameEvent event){ Queue<GameEvent> queue = this.events.get(id); if(queue == null){ throw new IllegalArgumentException("Id does not exist, id: " + id); } queue.offer(event); } public boolean addOpponentPlayer(byte id){ if(!events.containsKey(id)){ Logger.log("added player " + id); events.put(id, new LinkedList<GameEvent>()); game.addOpponentPlayer(id); return true; } return false; } public boolean addLocalPlayer(byte id) { if(!events.containsKey(id)){ for(byte i = 1; i < id;i++){ addOpponentPlayer(i); } events.put(id, new LinkedList<GameEvent>()); game.addLocalPlayer(id); this.localId = id; return true; } return false; } public boolean removePlayer(byte id) { if(!events.containsKey(id)){ game.removePlayer(id); } return false; } public void removeLocalPlayer() { if(localId > -1) this.removePlayer(localId); } }
package com.unidev.polygateway.service; import com.unidev.polygateway.data.ServiceMapping; import com.unidev.polygateway.data.ServiceMappingRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; /** * Service which identify service by url pattern */ @Service public class ServiceMapper { private static Logger LOG = LoggerFactory.getLogger(ServiceMapping.class); @Autowired private ServiceMappingRepository serviceMappingRepository; /** * List all services * @return */ public List<ServiceMapping> list() { return serviceMappingRepository.findAll(); } /** * Add/Update entity * @param serviceMapping * @return */ public ServiceMapping add(ServiceMapping serviceMapping) { return serviceMappingRepository.save(serviceMapping); } /** * Remove entity by id * @param id */ public void remove(String id) { serviceMappingRepository.delete(id); } /** * Fetch service mapping by external name * @return */ public Optional<ServiceMapping> match(String externalServiceName) { ServiceMapping serviceMapping = serviceMappingRepository.findOne(externalServiceName); if (serviceMapping != null) { return Optional.of(serviceMapping); } return Optional.empty(); } }
package cn.okayj.axui; import android.annotation.TargetApi; import android.content.Context; import android.graphics.drawable.Drawable; import android.support.annotation.IntDef; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; public class FlowLayout extends ViewGroup { @IntDef({HORIZONTAL,VERTICAL}) public @interface OrientationMode{} public static final int HORIZONTAL = 0; public static final int VERTICAL = 1; private static final int BAND_WIDTH_NOT_FIXED = 0; private int mOrientation = HORIZONTAL; private int mGravity = Gravity.START | Gravity.TOP; private int mBandWidth = BAND_WIDTH_NOT_FIXED; private Drawable mDivider; private Drawable mGap;//space between views private int mDividerWidth; private int mDividerHeight; private int mGapWidth; private int mGapHeight; private List<Band> mBands = new ArrayList<>(); public FlowLayout(Context context) { this(context,null); } public FlowLayout(Context context, AttributeSet attrs) { this(context,attrs,0); } public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context,attrs,defStyleAttr,0); } @TargetApi(21) public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context, attrs, defStyleAttr, defStyleRes); } private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes){ // TODO: 16/8/20 } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { mBands.clear(); int width = 0; int height = 0; int flowLength = 0;//flow orientation dimension int flowWidth = 0; final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int heightMode = MeasureSpec.getMode(heightMeasureSpec); final int widthSize = MeasureSpec.getSize(widthMeasureSpec); final int heightSize = MeasureSpec.getSize(heightMeasureSpec); final int flowLengthMode; final int flowLengthSize; final int flowWidthMode; final int flowWidthSize; if(mOrientation == HORIZONTAL){ flowLengthMode = widthMode; flowLengthSize = widthSize; flowWidthMode = heightMode; flowWidthSize = heightSize; }else { flowLengthMode = heightMode; flowLengthSize = heightSize; flowWidthMode = widthMode; flowWidthSize = widthSize; } switch (flowLengthMode){ case MeasureSpec.EXACTLY: flowLength = flowLengthSize; break; } switch (flowWidthMode){ case MeasureSpec.EXACTLY: flowWidth = flowLengthSize; break; } Band band; int bandWidth = 0; int bandLength = 0; boolean newBand = true; int childCount = getChildCount(); for(int i = 0; i < childCount; ++i){ View child = getChildAt(i); if(child.getVisibility() == GONE) continue; LayoutParams lp = (LayoutParams) child.getLayoutParams(); if(newBand){ bandLength = 0; band = new Band(); band.setStartIndex(0); if(mBandWidth != BAND_WIDTH_NOT_FIXED) band.setBandWidth(mBandWidth); mBands.add(band); newBand = false; } band = mBands.get(mBands.size() - 1); if(flowLengthMode == MeasureSpec.EXACTLY){ int preBandLength = bandLength; bandLength += } } // TODO: 16/8/20 } void measureHorizontal(int widthMeasureSpec, int heightMeasureSpec) { int width = 0; int height = 0; final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int heightMode = MeasureSpec.getMode(heightMeasureSpec); final int widthSize = MeasureSpec.getSize(widthMeasureSpec); final int heightSize = MeasureSpec.getSize(heightMeasureSpec); boolean fixedBandWidth = mBandWidth != BAND_WIDTH_NOT_FIXED; final int CONTENT_OCCUPIED_HORIZONTAL = getContentOccupied(HORIZONTAL); final int CONTENT_OCCUPIED_VERTICAL = getContentOccupied(VERTICAL); final int CONTENT_WIDTH = Math.max(0,widthSize - CONTENT_OCCUPIED_HORIZONTAL); final int CONTENT_HEIGHT = Math.max(0,heightSize - CONTENT_OCCUPIED_VERTICAL); Band band; int bandWidth = 0; int preBandWidth = bandWidth; int bandLength = 0; int preBandLength = bandLength; int tempBandLength = 0; int maxBandLength = 0;//band, int contentHeight = 0; boolean newBand = true; int childCount = getChildCount(); for(int i = 0; i < childCount - 1; ++i){ View child = getChildAt(i); if(child.getVisibility() == GONE){ continue; } LayoutParams lp = (LayoutParams) child.getLayoutParams(); int wMeasureSpec; int hMeasureSpec; boolean reMeasure = false; if(fixedBandWidth){ /* child */ if(lp.height == LayoutParams.MATCH_PARENT){ hMeasureSpec = MeasureSpec.makeMeasureSpec(getChildMeasureSize(mBandWidth - lp.topMargin - lp.bottomMargin),MeasureSpec.EXACTLY); }else{ hMeasureSpec = MeasureSpec.makeMeasureSpec(getChildMeasureSize(mBandWidth - lp.topMargin - lp.bottomMargin),MeasureSpec.AT_MOST); } }else { if(heightMode == MeasureSpec.UNSPECIFIED){ hMeasureSpec = MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED); }else { hMeasureSpec = MeasureSpec.makeMeasureSpec(getChildMeasureSize(CONTENT_HEIGHT - lp.topMargin - lp.bottomMargin), heightMode);// TODO: 16/8/27 ok? } } if(widthMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.AT_MOST){ tempBandLength = bandLength + lp.leftMargin + lp.rightMargin + mGapWidth; if(!newBand && CONTENT_WIDTH < tempBandLength){ //margin, newBand = true; preBandLength = bandLength; bandLength = 0; tempBandLength = bandLength + lp.leftMargin + lp.rightMargin + mGapWidth; } if(lp.width == LayoutParams.MATCH_PARENT){ wMeasureSpec = MeasureSpec.makeMeasureSpec(getChildMeasureSize(CONTENT_WIDTH - tempBandLength),MeasureSpec.EXACTLY); }else { wMeasureSpec = MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED); } child.measure(wMeasureSpec,hMeasureSpec); if(!newBand && bandLength + child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin > CONTENT_WIDTH){ reMeasure = true; newBand = true; preBandLength = bandLength; bandLength = 0; preBandWidth = bandWidth; bandWidth = 0; }else { bandLength += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin; bandWidth = Math.max(bandWidth,child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin); } }else{// widthMode == MeasureSpec.UNSPECIFIED wMeasureSpec = MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED); child.measure(wMeasureSpec,hMeasureSpec); }/*else {// AT_MOST }*/ if(reMeasure){ wMeasureSpec = MeasureSpec.makeMeasureSpec(CONTENT_WIDTH,widthMode); child.measure(wMeasureSpec,hMeasureSpec); bandWidth = Math.max(bandWidth,child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin); } if(newBand){ if(band != null){//set last band max width band.setBandWidth(preBandWidth); } bandLength = 0; band = new Band(); band.setStartIndex(i); mBands.add(band); newBand = false; maxBandLength = Math.max(preBandLength,maxBandLength); contentHeight += preBandWidth; } } //last band if(band != null){ band.setBandWidth(bandWidth); } int bandCount = mBands.size(); maxBandLength = Math.max(bandLength,maxBandLength); contentHeight += bandWidth; if(bandCount > 0){ contentHeight += (bandCount -1) * mDividerWidth; } width = maxBandLength + CONTENT_WIDTH; height = contentHeight + CONTENT_HEIGHT; width = Math.max(width,getSuggestedMinimumWidth()); height = Math.max(height,getSuggestedMinimumHeight()); setMeasuredDimension(resolveSize(width,widthMeasureSpec),resolveSize(height,heightMeasureSpec)); *//* /* *, int contentHeight = 0; int contentWidth = 0; int start = 0; int end = 0; band = null; for(int i = 0; i < mBands.size() - 1; ++i){ band = mBands.get(i); start = band.getStartIndex(); if(i < mBands.size() - 1){ end = mBands.get(i + 1).getStartIndex(); }else { end = getChildCount() - 1; } int maxChildHeight = 0; bandLength = 0; for(int childIndex = start; childCount <= end; ++childCount){ View child = getChildAt(childIndex); if(child.getVisibility() == GONE) continue; maxChildHeight = Math.max(maxChildHeight,child.getMeasuredHeight()); bandLength += child.getMeasuredWidth(); } band.setBandWidth(maxChildHeight); contentWidth = Math.max(contentWidth,bandLength); contentHeight += maxChildHeight; }*/ } private int getContentOccupied(@OrientationMode int orientation){ int occupied = 0; if(orientation == HORIZONTAL){ occupied += getPaddingLeft() + getPaddingRight(); if(mOrientation == HORIZONTAL){ int edgeGapCount = 0; // TODO: 16/8/27 count edge gap return occupied += mGapWidth * edgeGapCount; }else { return occupied; } }else { occupied += getPaddingTop() + getPaddingBottom(); if(mOrientation == VERTICAL){ int edgeGapCount = 0; // TODO: 16/8/27 count edge gap return occupied += mGapWidth * edgeGapCount; }else { return occupied; } } } private int getChildMeasureSize(int sizeLeft){ return Math.max(0,sizeLeft); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { // TODO: 16/8/20 } public final boolean isBandWidthFixed(){ return mBandWidth != BAND_WIDTH_NOT_FIXED; } public void setBandWidth(int bandWidth){ if(bandWidth <= 0) bandWidth = BAND_WIDTH_NOT_FIXED; if(bandWidth != mBandWidth){ mBandWidth = bandWidth; requestLayout(); } } public void setOrientation(@OrientationMode int orientation) { if (mOrientation != orientation) { mOrientation = orientation; requestLayout(); } } public void setGravity(int gravity){ if (mGravity != gravity) { if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { gravity |= Gravity.START; } if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { gravity |= Gravity.TOP; } mGravity = gravity; requestLayout(); } } public void setDividerDrawable(Drawable divider) { if (divider == mDivider) { return; } mDivider = divider; if (divider != null) { mDividerWidth = divider.getIntrinsicWidth(); mDividerHeight = divider.getIntrinsicHeight(); } else { mDividerWidth = 0; mDividerHeight = 0; } setWillNotDraw(mDivider == null && mGap == null); requestLayout(); } public void setGapDrawable(Drawable gap){ if (gap == mGap) { return; } mGap = gap; if (gap != null) { mGapWidth = gap.getIntrinsicWidth(); mGapHeight = gap.getIntrinsicHeight(); } else { mGapWidth = 0; mGapHeight = 0; } setWillNotDraw(mDivider == null && mGap == null); requestLayout(); } public static class LayoutParams extends ViewGroup.MarginLayoutParams { private boolean mCR = false; public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); //// TODO: 16/8/20 } public LayoutParams(int width, int height) { super(width, height); } public LayoutParams(MarginLayoutParams source) { super(source); } public LayoutParams(ViewGroup.LayoutParams source) { super(source); } public LayoutParams(LayoutParams source){ super(source); //// TODO: 16/8/20 } } private static class Band { private int mBandContentMaxWidth; private int mStartIndex;//start child index public int getBandWidth() { return mBandContentMaxWidth; } public void setBandWidth(int bandContentMaxWidth) { this.mBandContentMaxWidth = bandContentMaxWidth; } public int getStartIndex() { return mStartIndex; } public void setStartIndex(int startIndex) { this.mStartIndex = startIndex; } } }
package com.facebook.presto.server; import com.facebook.presto.importer.ForPeriodicImport; import com.facebook.presto.importer.JobStateFactory; import com.facebook.presto.importer.PeriodicImportConfig; import com.facebook.presto.importer.PeriodicImportController; import com.facebook.presto.importer.PeriodicImportJobResource; import com.facebook.presto.importer.PeriodicImportManager; import com.facebook.presto.importer.PeriodicImportRunnable; import com.facebook.presto.event.query.QueryCompletionEvent; import com.facebook.presto.event.query.QueryCreatedEvent; import com.facebook.presto.event.query.QueryMonitor; import com.facebook.presto.execution.FailureInfo; import com.facebook.presto.execution.LocationFactory; import com.facebook.presto.execution.QueryInfo; import com.facebook.presto.execution.QueryManager; import com.facebook.presto.execution.QueryManagerConfig; import com.facebook.presto.execution.RemoteTaskFactory; import com.facebook.presto.execution.SqlQueryManager; import com.facebook.presto.execution.SqlTaskManager; import com.facebook.presto.execution.StageInfo; import com.facebook.presto.execution.TaskInfo; import com.facebook.presto.execution.TaskManager; import com.facebook.presto.importer.ForImportManager; import com.facebook.presto.importer.ImportManager; import com.facebook.presto.importer.LocalShardManager; import com.facebook.presto.importer.NodeWorkerQueue; import com.facebook.presto.importer.ShardImport; import com.facebook.presto.metadata.DatabaseShardManager; import com.facebook.presto.metadata.DatabaseStorageManager; import com.facebook.presto.metadata.ForMetadata; import com.facebook.presto.metadata.ForShardManager; import com.facebook.presto.metadata.ForStorageManager; import com.facebook.presto.metadata.ImportMetadata; import com.facebook.presto.metadata.InformationSchemaData; import com.facebook.presto.metadata.InformationSchemaMetadata; import com.facebook.presto.metadata.InternalMetadata; import com.facebook.presto.metadata.Metadata; import com.facebook.presto.metadata.MetadataManager; import com.facebook.presto.metadata.MetadataResource; import com.facebook.presto.metadata.NativeMetadata; import com.facebook.presto.metadata.NodeManager; import com.facebook.presto.metadata.ShardManager; import com.facebook.presto.metadata.StorageManager; import com.facebook.presto.metadata.StorageManagerConfig; import com.facebook.presto.metadata.SystemTables; import com.facebook.presto.metadata.HandleJsonModule; import com.facebook.presto.operator.ForExchange; import com.facebook.presto.operator.ForScheduler; import com.facebook.presto.spi.ImportClientFactory; import com.facebook.presto.split.DataStreamManager; import com.facebook.presto.split.DataStreamProvider; import com.facebook.presto.split.ImportClientManager; import com.facebook.presto.split.ImportDataStreamProvider; import com.facebook.presto.split.InternalDataStreamProvider; import com.facebook.presto.split.NativeDataStreamProvider; import com.facebook.presto.split.Split; import com.facebook.presto.split.SplitManager; import com.facebook.presto.sql.tree.Expression; import com.facebook.presto.sql.tree.FunctionCall; import com.facebook.presto.sql.tree.Serialization.ExpressionDeserializer; import com.facebook.presto.sql.tree.Serialization.ExpressionSerializer; import com.facebook.presto.sql.tree.Serialization.FunctionCallDeserializer; import com.google.inject.Provides; import com.google.inject.Scopes; import com.google.inject.multibindings.Multibinder; import io.airlift.dbpool.H2EmbeddedDataSource; import io.airlift.dbpool.H2EmbeddedDataSourceConfig; import io.airlift.dbpool.H2EmbeddedDataSourceModule; import io.airlift.dbpool.MySqlDataSourceModule; import io.airlift.discovery.client.ServiceAnnouncement.ServiceAnnouncementBuilder; import io.airlift.http.client.HttpClientBinder; import io.airlift.units.Duration; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.IDBI; import org.weakref.jmx.guice.ExportBinder; import javax.inject.Singleton; import java.io.File; import java.lang.annotation.Annotation; import static com.facebook.presto.server.ConditionalModule.installIfPropertyEquals; import static com.facebook.presto.server.DbiProvider.bindDbiToDataSource; import static io.airlift.configuration.ConfigurationModule.bindConfig; import static io.airlift.discovery.client.DiscoveryBinder.discoveryBinder; import static io.airlift.event.client.EventBinder.eventBinder; import static io.airlift.http.client.HttpClientBinder.httpClientBinder; import static io.airlift.json.JsonBinder.jsonBinder; import static io.airlift.json.JsonCodecBinder.jsonCodecBinder; import static java.util.concurrent.TimeUnit.SECONDS; public class ServerMainModule extends AbstractConfigurationAwareModule { @Override protected void configure() { binder.bind(QueryResource.class).in(Scopes.SINGLETON); binder.bind(QueryManager.class).to(SqlQueryManager.class).in(Scopes.SINGLETON); bindConfig(binder).to(QueryManagerConfig.class); binder.bind(TaskResource.class).in(Scopes.SINGLETON); binder.bind(TaskManager.class).to(SqlTaskManager.class).in(Scopes.SINGLETON); binder.bind(ExchangeOperatorFactory.class).in(Scopes.SINGLETON); jsonCodecBinder(binder).bindJsonCodec(TaskInfo.class); binder.bind(PagesMapper.class).in(Scopes.SINGLETON); binder.bind(LocationFactory.class).to(HttpLocationFactory.class).in(Scopes.SINGLETON); binder.bind(RemoteTaskFactory.class).to(HttpRemoteTaskFactory.class).in(Scopes.SINGLETON); HttpClientBinder.httpClientBinder(binder).bindAsyncHttpClient("exchange", ForExchange.class).withTracing(); HttpClientBinder.httpClientBinder(binder).bindHttpClient("scheduler", ForScheduler.class).withTracing(); bindConfig(binder).to(StorageManagerConfig.class); binder.bind(StorageManager.class).to(DatabaseStorageManager.class).in(Scopes.SINGLETON); binder.bind(DataStreamProvider.class).to(DataStreamManager.class).in(Scopes.SINGLETON); binder.bind(NativeDataStreamProvider.class).in(Scopes.SINGLETON); binder.bind(ImportDataStreamProvider.class).in(Scopes.SINGLETON); binder.bind(Metadata.class).to(MetadataManager.class).in(Scopes.SINGLETON); binder.bind(NativeMetadata.class).in(Scopes.SINGLETON); binder.bind(MetadataResource.class).in(Scopes.SINGLETON); binder.bind(InternalMetadata.class).in(Scopes.SINGLETON); binder.bind(InternalDataStreamProvider.class).in(Scopes.SINGLETON); binder.bind(InformationSchemaMetadata.class).in(Scopes.SINGLETON); binder.bind(InformationSchemaData.class).in(Scopes.SINGLETON); binder.bind(SystemTables.class).in(Scopes.SINGLETON); binder.bind(ImportClientManager.class).in(Scopes.SINGLETON); // kick off binding of import client factories Multibinder.newSetBinder(binder, ImportClientFactory.class); binder.bind(ImportMetadata.class).in(Scopes.SINGLETON); binder.bind(SplitManager.class).in(Scopes.SINGLETON); jsonCodecBinder(binder).bindJsonCodec(QueryFragmentRequest.class); jsonCodecBinder(binder).bindJsonCodec(Split.class); jsonBinder(binder).addSerializerBinding(Expression.class).to(ExpressionSerializer.class); jsonBinder(binder).addDeserializerBinding(Expression.class).to(ExpressionDeserializer.class); jsonBinder(binder).addDeserializerBinding(FunctionCall.class).to(FunctionCallDeserializer.class); jsonCodecBinder(binder).bindJsonCodec(StageInfo.class); jsonCodecBinder(binder).bindListJsonCodec(FailureInfo.class); binder.bind(QueryMonitor.class).in(Scopes.SINGLETON); eventBinder(binder).bindEventClient(QueryCreatedEvent.class); eventBinder(binder).bindEventClient(QueryCompletionEvent.class); discoveryBinder(binder).bindSelector("presto"); binder.bind(NodeManager.class).in(Scopes.SINGLETON); binder.bind(NodeWorkerQueue.class).in(Scopes.SINGLETON); binder.bind(ShardManager.class).to(DatabaseShardManager.class).in(Scopes.SINGLETON); binder.bind(ImportManager.class).in(Scopes.SINGLETON); httpClientBinder(binder).bindHttpClient("importer", ForImportManager.class).withFilter(NodeIdUserAgentRequestFilter.class); binder.bind(LocalShardManager.class).in(Scopes.SINGLETON); binder.bind(ShardResource.class).in(Scopes.SINGLETON); jsonCodecBinder(binder).bindJsonCodec(ShardImport.class); ServiceAnnouncementBuilder announcementBuilder = discoveryBinder(binder).bindHttpAnnouncement("presto"); String datasources = configurationFactory.getProperties().get("datasources"); if (datasources != null) { configurationFactory.consumeProperty("datasources"); announcementBuilder.addProperty("datasources", datasources); } String coordinatorProperty = configurationFactory.getProperties().get("coordinator"); if (coordinatorProperty != null) { configurationFactory.consumeProperty("coordinator"); } // default coordinator value is true if (coordinatorProperty == null || Boolean.parseBoolean(coordinatorProperty)) { discoveryBinder(binder).bindHttpAnnouncement("presto-coordinator"); } bindDataSource("presto-metastore", ForMetadata.class, ForShardManager.class, ForPeriodicImport.class); jsonCodecBinder(binder).bindJsonCodec(QueryInfo.class); jsonCodecBinder(binder).bindJsonCodec(TaskInfo.class); binder.bind(ExecuteResource.class).in(Scopes.SINGLETON); httpClientBinder(binder).bindAsyncHttpClient("execute", ExecuteResource.ForExecute.class); binder.install(new HandleJsonModule()); binder.bind(PluginManager.class).in(Scopes.SINGLETON); bindConfig(binder).to(PluginManagerConfig.class); // Job Scheduler code bindConfig(binder).to(PeriodicImportConfig.class); binder.bind(PeriodicImportJobResource.class).in(Scopes.SINGLETON); binder.bind(PeriodicImportManager.class).in(Scopes.SINGLETON); binder.bind(PeriodicImportController.class).in(Scopes.SINGLETON); binder.bind(JobStateFactory.class).in(Scopes.SINGLETON); binder.bind(PeriodicImportRunnable.PeriodicImportRunnableFactory.class).in(Scopes.SINGLETON); ExportBinder.newExporter(binder).export(PeriodicImportController.class).as("com.facebook.presto:name=periodic-import"); } @Provides @Singleton @ForStorageManager public IDBI createStorageManagerDBI(StorageManagerConfig config) throws Exception { String path = new File(config.getDataDirectory(), "db/StorageManager").getAbsolutePath(); return new DBI(new H2EmbeddedDataSource(new H2EmbeddedDataSourceConfig().setFilename(path).setMaxConnections(500).setMaxConnectionWait(new Duration(1, SECONDS)))); } @SafeVarargs private final void bindDataSource(String type, Class<? extends Annotation> annotation, Class<? extends Annotation>... aliases) { String property = type + ".db.type"; install(installIfPropertyEquals(new MySqlDataSourceModule(type, annotation, aliases), property, "mysql")); install(installIfPropertyEquals(new H2EmbeddedDataSourceModule(type, annotation, aliases), property, "h2")); bindDbiToDataSource(binder, annotation); for (Class<? extends Annotation> alias : aliases) { bindDbiToDataSource(binder, alias); } } }
package ca.nrc.cadc.vos; import static org.junit.Assert.assertEquals; import java.nio.charset.Charset; import java.security.MessageDigest; import org.junit.Before; import org.junit.Test; import ca.nrc.cadc.util.FileMetadata; public abstract class VOSpaceFileMetadataSourceTest extends AbstractPersistenceTest { private VOSpaceFileMetadataSource vospaceFileMetadataSource; private VOSURI testURI; private DataNode testNode; public VOSpaceFileMetadataSourceTest() { super(); } @Before public void before() throws Exception { super.commonBefore(); vospaceFileMetadataSource = new VOSpaceFileMetadataSource(); vospaceFileMetadataSource.setNodePersistence(nodeDAO); ContainerNode rootContainer = (ContainerNode) nodeDAO.getFromParent(getRootContainerName(), null); testURI = new VOSURI(getVOSURIPrefix() + "/" + getRootContainerName() + "/" + getNodeName("testNode")); testNode = new DataNode(testURI); testNode.setOwner(getNodeOwner()); nodeDAO.putInContainer(testNode, rootContainer); } @Test public void testMetadata() throws Exception { String contentEncoding = "gzip"; Long contentLength = 256L; String contentType = "text/xml"; String md5SumSource = "valuetohashis a longer string now."; MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(md5SumSource.getBytes("iso-8859-1"), 0, md5SumSource.length()); byte[] md5hash = md.digest(); String contentMD5 = new String(md5hash, Charset.forName("iso-8859-1")); FileMetadata metadata1 = new FileMetadata(); metadata1.setContentEncoding(contentEncoding); metadata1.setContentLength(contentLength); metadata1.setContentType(contentType); metadata1.setMd5Sum(contentMD5); vospaceFileMetadataSource.set(testURI.getURIObject(), metadata1); FileMetadata metadata2 = vospaceFileMetadataSource.get(testURI.getURIObject()); assertEquals(contentEncoding, metadata2.getContentEncoding()); assertEquals(contentLength, metadata2.getContentLength()); assertEquals(contentType, metadata2.getContentType()); assertEquals(contentMD5, metadata2.getMd5Sum()); } }
package drat.proteus.filemgr.rest; import backend.FileConstants; import org.apache.oodt.cas.filemgr.structs.ProductType; import org.apache.oodt.cas.filemgr.structs.exceptions.CatalogException; import org.apache.oodt.cas.filemgr.structs.exceptions.ConnectionException; import org.apache.oodt.cas.filemgr.system.XmlRpcFileManagerClient; import org.apache.oodt.cas.metadata.Metadata; import org.apache.oodt.cas.metadata.util.PathUtils; import org.wicketstuff.rest.annotations.MethodMapping; import org.wicketstuff.rest.contenthandling.json.webserialdeserial.GsonWebSerialDeserial; import org.wicketstuff.rest.resource.AbstractRestResource; import org.wicketstuff.rest.utils.http.HttpMethod; import java.net.URL; import java.util.Collections; import java.util.logging.Logger; public class FileManagerRestResource extends AbstractRestResource<GsonWebSerialDeserial> { private static final long serialVersionUID = -588588505908995065L; XmlRpcFileManagerClient fileManagerClient; private static final Logger LOG = Logger.getLogger(FileManagerRestResource.class.getName()); public FileManagerRestResource() { super(new GsonWebSerialDeserial()); try{ fileManagerClient = new XmlRpcFileManagerClient(new URL(PathUtils.replaceEnvVariables(FileConstants.FILEMGR_URL))); }catch (Exception ex){ LOG.severe(ex.getMessage()); } } @MethodMapping(value = "/progress",httpMethod = HttpMethod.GET) public FileManagerProgressResponse getProgress() throws Exception { FileManagerProgressResponse response = new FileManagerProgressResponse(); response.crawledFiles = fileManagerClient.getNumProducts(fileManagerClient.getProductTypeByName("GenericFile")); return response; } }
package uk.org.ponder.rsf.viewstate; import java.util.HashMap; import java.util.Map; import uk.org.ponder.reflect.DeepBeanCloner; import uk.org.ponder.reflect.ReflectiveCache; import uk.org.ponder.util.Logger; /** * A simple parser of view parameters, which will parse into clones of supplied * "exemplar" objects. The lookup will be performed on the first segment of the * pathinfo (up to first slash), which will be assumed to represent the viewID. * * @author Antranig Basman (antranig@caret.cam.ac.uk) * */ public class BasicViewParametersParser implements ViewParametersParser, ViewParamsReceiver { private Map exemplarmap; private ViewParamsMapper vpmapper; private DeepBeanCloner beancloner; private ViewIDInferrer viewIDInferrer; public void setViewParamsMapper(ViewParamsMapper vpmapper) { this.vpmapper = vpmapper; } public void setDeepBeanCloner(DeepBeanCloner beancloner) { this.beancloner = beancloner; } public void setViewIDInferrer(ViewIDInferrer viewIDInferrer) { this.viewIDInferrer = viewIDInferrer; } // A single-threaded hashmap to be used during startup. private Map pendingmap = new HashMap(); private ViewParameters defaultexemplar = new SimpleViewParameters(); private String defaultview; // Called from ConcreteViewResolver.init(), i.e. "somewhat late" public void setDefaultView(String viewid) { defaultview = viewid; } /** * DO NOT call this method in application scope. Default view cannot be * guaranteed to be called until all views are read. * * @return The default view to be redirected to in case of a Level-1 * exception. */ public String getDefaultView() { if (defaultview == null) { Logger.log .warn("Warning: no view has been marked as default during initialisation -" + "\nDid you remember to define ViewProducers?"); } return "/" + defaultview; } /** * AT MOST ONE view parameters map may be set as "pending" during startup * (presumably through reading of a static file). It will be actioned on * initialisation of the bean, all further will be actioned immediately. */ public void setViewParametersMap(Map exemplarmap) { (this.exemplarmap == null ? pendingmap : this.exemplarmap).putAll(exemplarmap); } public void setViewParamsExemplar(String viewid, ViewParameters vpexemplar) { if (vpexemplar != null) { (exemplarmap == null ? pendingmap : exemplarmap).put(viewid, vpexemplar); } } public void setReflectiveCache(ReflectiveCache reflectivecache) { exemplarmap = reflectivecache.getConcurrentMap(1); } public void init() { exemplarmap.putAll(pendingmap); pendingmap = null; } public void setDefaultExemplar(ViewParameters defaultexemplar) { this.defaultexemplar = defaultexemplar; } public ViewParameters parse(String pathinfo, Map requestmap) { // JSF memorial comment: // restoreView is the very first of the ViewHandler methods to be called for // each request, and it is guaranteed to be called. We take this opportunity // to stash away a parsed parameter object corresponding to our original // request. String viewID = viewIDInferrer.inferViewID(pathinfo, requestmap); ViewParameters vpexemplar = (ViewParameters) exemplarmap.get(viewID); if (vpexemplar == null) { vpexemplar = defaultexemplar; } ViewParameters origrequest = vpexemplar.copyBase(beancloner); vpmapper.parseViewParamAttributes(origrequest, requestmap); origrequest.parsePathInfo(pathinfo); // this may *disagree* with value forced in by parsePathInfo due to VII origrequest.viewID = viewID; // Map requestmap = req. // requestmap.put(ViewParameters.CURRENT_REQUEST, origrequest); if (Logger.log.isDebugEnabled()) { Logger.log.debug("Parsed view " + origrequest.viewID + " from request parameters " + vpmapper.toHTTPRequest(origrequest)); } return origrequest; } }
package cgeo.geocaching.maps; import cgeo.geocaching.R; import cgeo.geocaching.databinding.MapSettingsDialogBinding; import cgeo.geocaching.filters.core.GeocacheFilter; import cgeo.geocaching.filters.core.GeocacheFilterContext; import cgeo.geocaching.maps.routing.Routing; import cgeo.geocaching.maps.routing.RoutingMode; import cgeo.geocaching.models.IndividualRoute; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.storage.PersistableUri; import cgeo.geocaching.ui.ImageParam; import cgeo.geocaching.ui.TextParam; import cgeo.geocaching.ui.ViewUtils; import cgeo.geocaching.ui.dialog.Dialogs; import cgeo.geocaching.ui.dialog.SimpleDialog; import cgeo.geocaching.utils.IndividualRouteUtils; import cgeo.geocaching.utils.functions.Action1; import android.app.Activity; import android.app.Dialog; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.LinearLayout; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import static java.lang.Boolean.TRUE; import com.google.android.material.button.MaterialButtonToggleGroup; import org.apache.commons.lang3.tuple.ImmutablePair; public class MapSettingsUtils { private static boolean isShowCircles; private static boolean isAutotargetIndividualRoute; private static boolean showAutotargetIndividualRoute; private MapSettingsUtils() { // utility class } @SuppressWarnings({"PMD.NPathComplexity", "PMD.ExcessiveMethodLength"}) // splitting up that method would not help improve readability public static void showSettingsPopup(final Activity activity, @Nullable final IndividualRoute route, @NonNull final Action1<Boolean> onMapSettingsPopupFinished, @NonNull final Action1<RoutingMode> setRoutingValue, @NonNull final Action1<Integer> setCompactIconValue, final GeocacheFilterContext filterContext) { isShowCircles = Settings.isShowCircles(); isAutotargetIndividualRoute = Settings.isAutotargetIndividualRoute(); showAutotargetIndividualRoute = isAutotargetIndividualRoute || (route != null && route.getNumSegments() > 0); final GeocacheFilter filter = filterContext.get(); final Map<GeocacheFilter.QuickFilter, Boolean> quickFilter = filter.getQuickFilter(); final ArrayList<SettingsCheckboxModel> allCbs = new ArrayList<>(); final SettingsCheckboxModel foundCb = createCb(allCbs, R.string.map_showc_found, ImageParam.id(R.drawable.marker_found), quickFilter.get(GeocacheFilter.QuickFilter.FOUND), f -> quickFilter.put(GeocacheFilter.QuickFilter.FOUND, f), false); final SettingsCheckboxModel offlineLogCb = createCb(allCbs, R.string.map_showc_offlinelog, R.drawable.marker_found_offline, quickFilter.get(GeocacheFilter.QuickFilter.HAS_OFFLINE_LOG), f -> quickFilter.put(GeocacheFilter.QuickFilter.HAS_OFFLINE_LOG, f), false); final SettingsCheckboxModel ownCb = createCb(allCbs, R.string.map_showc_own, ImageParam.id(R.drawable.marker_own), quickFilter.get(GeocacheFilter.QuickFilter.OWNED), f -> quickFilter.put(GeocacheFilter.QuickFilter.OWNED, f), false); final SettingsCheckboxModel disabledCb = createCb(allCbs, R.string.map_showc_disabled, R.drawable.map_status_disabled, quickFilter.get(GeocacheFilter.QuickFilter.DISABLED), f -> quickFilter.put(GeocacheFilter.QuickFilter.DISABLED, f), false); final SettingsCheckboxModel archivedCb = createCb(allCbs, R.string.map_showc_archived, R.drawable.map_status_archived, quickFilter.get(GeocacheFilter.QuickFilter.ARCHIVED), f -> quickFilter.put(GeocacheFilter.QuickFilter.ARCHIVED, f), false); final SettingsCheckboxModel wpOriginalCb = createCb(allCbs, R.string.map_showwp_original, R.drawable.waypoint_waypoint, Settings.isExcludeWpOriginal(), Settings::setExcludeWpOriginal, true); final SettingsCheckboxModel wpParkingCb = createCb(allCbs, R.string.map_showwp_parking, R.drawable.waypoint_pkg, Settings.isExcludeWpParking(), Settings::setExcludeWpParking, true); final SettingsCheckboxModel wbVisitedCb = createCb(allCbs, R.string.map_showwp_visited, R.drawable.tick, Settings.isExcludeWpVisited(), Settings::setExcludeWpVisited, true); final SettingsCheckboxModel trackCb = !PersistableUri.TRACK.hasValue() ? null : createCb(allCbs, R.string.map_show_track, R.drawable.map_hidetrack, Settings.isHideTrack(), Settings::setHideTrack, true); final SettingsCheckboxModel circlesCb = createCb(allCbs, R.string.map_show_circles, R.drawable.map_circle, isShowCircles, Settings::setShowCircles, false); final MapSettingsDialogBinding dialogView = MapSettingsDialogBinding.inflate(LayoutInflater.from(Dialogs.newContextThemeWrapper(activity))); final List<LinearLayout> columns = ViewUtils.createAndAddStandardColumnView(activity, dialogView.mapSettingsColumns, null, 2, true); final LinearLayout leftColumn = columns.get(0); final LinearLayout rightColumn = columns.get(1); final boolean disableCacheFilters = !filter.canSetQuickFilterLossless(); leftColumn.addView(ViewUtils.createTextItem(activity, R.style.map_quicksettings_subtitle, TextParam.id(R.string.map_show_caches_title))); foundCb.addToViewGroup(activity, leftColumn, disableCacheFilters); offlineLogCb.addToViewGroup(activity, leftColumn, disableCacheFilters); ownCb.addToViewGroup(activity, leftColumn, disableCacheFilters); disabledCb.addToViewGroup(activity, leftColumn, disableCacheFilters); archivedCb.addToViewGroup(activity, leftColumn, disableCacheFilters); rightColumn.addView(ViewUtils.createTextItem(activity, R.style.map_quicksettings_subtitle, TextParam.id(R.string.map_show_waypoints_title))); wpOriginalCb.addToViewGroup(activity, rightColumn); wpParkingCb.addToViewGroup(activity, rightColumn); wbVisitedCb.addToViewGroup(activity, rightColumn); rightColumn.addView(ViewUtils.createTextItem(activity, R.style.map_quicksettings_subtitle, TextParam.id(R.string.map_show_other_title))); if (trackCb != null) { trackCb.addToViewGroup(activity, rightColumn); } circlesCb.addToViewGroup(activity, rightColumn); final ToggleButtonWrapper<Integer> compactIconWrapper = new ToggleButtonWrapper<>(Settings.getCompactIconMode(), setCompactIconValue, dialogView.compacticonTooglegroup); compactIconWrapper.add(new ButtonChoiceModel<>(R.id.compacticon_off, Settings.COMPACTICON_OFF, activity.getString(R.string.switch_off))); compactIconWrapper.add(new ButtonChoiceModel<>(R.id.compacticon_auto, Settings.COMPACTICON_AUTO, activity.getString(R.string.switch_auto))); compactIconWrapper.add(new ButtonChoiceModel<>(R.id.compacticon_on, Settings.COMPACTICON_ON, activity.getString(R.string.switch_on))); final ToggleButtonWrapper<RoutingMode> routingChoiceWrapper = new ToggleButtonWrapper<>(Routing.isAvailable() || Settings.getRoutingMode() == RoutingMode.OFF ? Settings.getRoutingMode() : RoutingMode.STRAIGHT, setRoutingValue, dialogView.routingTooglegroup); for (RoutingMode mode : RoutingMode.values()) { routingChoiceWrapper.add(new ButtonChoiceModel<>(mode.buttonResId, mode, activity.getString(mode.infoResId))); } if (showAutotargetIndividualRoute) { dialogView.mapSettingsAutotargetContainer.setVisibility(View.VISIBLE); dialogView.mapSettingsAutotarget.setChecked(isAutotargetIndividualRoute); } final Dialog dialog = Dialogs.bottomSheetDialogWithActionbar(activity, dialogView.getRoot(), R.string.quick_settings); dialog.setOnDismissListener(d -> { for (SettingsCheckboxModel item : allCbs) { item.setValue(); } compactIconWrapper.setValue(); routingChoiceWrapper.setValue(); if (filter.canSetQuickFilterLossless() && !filter.hasSameQuickFilter(quickFilter)) { filter.setQuickFilterLossless(quickFilter); filterContext.set(filter); } onMapSettingsPopupFinished.call(isShowCircles != Settings.isShowCircles()); if (showAutotargetIndividualRoute && isAutotargetIndividualRoute != dialogView.mapSettingsAutotarget.isChecked()) { if (route == null) { Settings.setAutotargetIndividualRoute(dialogView.mapSettingsAutotarget.isChecked()); } else { IndividualRouteUtils.setAutotargetIndividualRoute(activity, route, dialogView.mapSettingsAutotarget.isChecked()); } } }); dialog.show(); compactIconWrapper.init(); routingChoiceWrapper.init(); if (!Routing.isAvailable()) { configureRoutingButtons(false, routingChoiceWrapper); dialogView.routingInfo.setVisibility(View.VISIBLE); dialogView.routingInfo.setOnClickListener(v -> SimpleDialog.of(activity).setTitle(R.string.map_routing_activate_title).setMessage(R.string.map_routing_activate).confirm((dialog1, which) -> { Settings.setUseInternalRouting(true); Settings.setBrouterAutoTileDownloads(true); configureRoutingButtons(true, routingChoiceWrapper); dialogView.routingInfo.setVisibility(View.GONE); })); } } private static void configureRoutingButtons(final boolean enabled, final ToggleButtonWrapper<RoutingMode> routingChoiceWrapper) { for (final ButtonChoiceModel<RoutingMode> button : routingChoiceWrapper.list) { if (!(button.assignedValue == RoutingMode.OFF || button.assignedValue == RoutingMode.STRAIGHT)) { button.button.setEnabled(enabled); button.button.setAlpha(enabled ? 1f : .3f); } } } private static SettingsCheckboxModel createCb(final Collection<SettingsCheckboxModel> coll, @StringRes final int resTitle, @DrawableRes final int resIcon, final Boolean currentValue, final Action1<Boolean> setValue, final boolean isNegated) { final SettingsCheckboxModel result = new SettingsCheckboxModel(resTitle, resIcon, currentValue, setValue, isNegated); coll.add(result); return result; } private static SettingsCheckboxModel createCb(final Collection<SettingsCheckboxModel> coll, @StringRes final int resTitle, final ImageParam imageParam, final Boolean currentValue, final Action1<Boolean> setValue, final boolean isNegated) { final SettingsCheckboxModel result = new SettingsCheckboxModel(resTitle, imageParam, currentValue, setValue, isNegated); coll.add(result); return result; } private static class SettingsCheckboxModel { @StringRes private final int resTitle; private final ImageParam imageParam; private boolean currentValue; private final Action1<Boolean> setValue; private final boolean isNegated; SettingsCheckboxModel(@StringRes final int resTitle, @DrawableRes final int resIcon, final Boolean currentValue, final Action1<Boolean> setValue, final boolean isNegated) { this.resTitle = resTitle; this.imageParam = ImageParam.id(resIcon); this.currentValue = isNegated != (TRUE.equals(currentValue)); this.setValue = setValue; this.isNegated = isNegated; } SettingsCheckboxModel(@StringRes final int resTitle, final ImageParam imageParam, final Boolean currentValue, final Action1<Boolean> setValue, final boolean isNegated) { this.resTitle = resTitle; this.imageParam = imageParam; this.currentValue = isNegated != (TRUE.equals(currentValue)); this.setValue = setValue; this.isNegated = isNegated; } public void setValue() { if (setValue != null) { this.setValue.call(isNegated != currentValue); } } public void addToViewGroup(final Activity ctx, final ViewGroup viewGroup) { addToViewGroup(ctx, viewGroup, false); } public void addToViewGroup(final Activity ctx, final ViewGroup viewGroup, final boolean disableView) { final ImmutablePair<View, CheckBox> ip = ViewUtils.createCheckboxItem(ctx, viewGroup, TextParam.id(resTitle), imageParam, null); viewGroup.addView(ip.left); if (disableView) { ip.right.setEnabled(false); ip.left.setOnClickListener(v -> SimpleDialog.of(ctx).setTitle(R.string.map_settings_cache_filter_too_complex_title) .setMessage(R.string.map_settings_cache_filter_too_complex_message).show()); } ip.right.setChecked(currentValue); ip.right.setOnCheckedChangeListener((v, c) -> this.currentValue = !this.currentValue); } } private static class ButtonChoiceModel<T> { public final int resButton; public final T assignedValue; public final String info; public View button = null; ButtonChoiceModel(final int resButton, final T assignedValue, final String info) { this.resButton = resButton; this.assignedValue = assignedValue; this.info = info; } } private static class ToggleButtonWrapper<T> { private final MaterialButtonToggleGroup toggleGroup; private final ArrayList<ButtonChoiceModel<T>> list; private final Action1<T> setValue; private final T originalValue; ToggleButtonWrapper(final T originalValue, final Action1<T> setValue, final MaterialButtonToggleGroup toggleGroup) { this.originalValue = originalValue; this.toggleGroup = toggleGroup; this.setValue = setValue; this.list = new ArrayList<>(); } public void add(final ButtonChoiceModel<T> item) { list.add(item); } public ButtonChoiceModel<T> getByResId(final int id) { for (ButtonChoiceModel<T> item : list) { if (item.resButton == id) { return item; } } return null; } public ButtonChoiceModel<T> getByAssignedValue(final T value) { for (ButtonChoiceModel<T> item : list) { if (Objects.equals(item.assignedValue, value)) { return item; } } return null; } public void init() { for (final ButtonChoiceModel<T> button : list) { button.button = toggleGroup.findViewById(button.resButton); } toggleGroup.check(getByAssignedValue(originalValue).resButton); } public void setValue() { final T currentValue = getByResId(toggleGroup.getCheckedButtonId()).assignedValue; if (setValue != null && !originalValue.equals(currentValue)) { this.setValue.call(currentValue); } } } }
package authoring.environment; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ResourceBundle; public class InstanceManager { private int partsCreated = 0; private static final String paramListFile = "resources/part_parameters"; private static final String paramSpecsFile = "resources/parameter_datatype"; //a map of all the parts the user has created //each part is represented by a map mapping the part's parameters to their data //the fields look like: Map<partName, Map<parameterName, parameterData>> private Map<String, Map<String, Object>> userParts; public InstanceManager(){ userParts = new HashMap<String, Map<String, Object>>(); } //adds a default part to userParts with the name "Part_x" where x the number of parts the user has created public Map<String, Object> addPart(String partType){ Map<String, Object> newPart = createDefaultPart(partType); String partName = "Part_" + new Integer(partsCreated++).toString() + "." + partType; userParts.put(partName, newPart); return newPart; } public static String getPartType(Class c){ return c.toString().substring(0, c.toString().indexOf("Editor")); } public void updatePart(String partName, String param, String newData){ Map<String, Object> partToBeUpdated = userParts.get(partName); Object data = "data incorrectly added"; try { data = partToBeUpdated.get(param).getClass().getConstructor(String.class).newInstance(newData); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } partToBeUpdated.put(param, data); } //creates a default part of partType's type public Map<String, Object> createDefaultPart(String partType){ Map<String, Object> part = new HashMap<String, Object>(); ResourceBundle paramLists = ResourceBundle.getBundle(paramListFile); ResourceBundle paramSpecs = ResourceBundle.getBundle(paramSpecsFile); String[] params = paramLists.getString(partType).split("\\s+"); for(String paramName : params){ String[] typeAndDefault = paramSpecs.getString(paramName).split("\\s+"); String dataType = typeAndDefault[0]; String defaultVal = typeAndDefault[1]; part.put(paramName, makeDefaultData(dataType, defaultVal)); } return part; } //creates an Object of class "dataType" and value "defualtVal" private Object makeDefaultData(String dataType, String defaultVal){ Class<?> c = Integer.class; Object data = new Integer("0"); try{ c = Class.forName(dataType); }catch (ClassNotFoundException e){ System.out.println(dataType + "class not found"); //do something, but this shouldn't happen if the properties file is correct } try{ data = c.getConstructor(String.class).newInstance(defaultVal); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e){ //hopefully this won't happen System.out.println("Constructor couldn't be called with a String"); } return data; } @Override public String toString(){ StringBuilder toPrint = new StringBuilder(); for(String partName : userParts.keySet()) toPrint.append("Name: ") .append(partName) .append(", Params: ") .append(userParts.get(partName).toString()) .append("\n"); return toPrint.toString(); } public static void main (String[] args){ InstanceManager gameManager = new InstanceManager(); gameManager.addPart("Tower"); gameManager.addPart("Unit"); gameManager.addPart("Projectile"); gameManager.addPart("Projectile"); gameManager.addPart("Unit"); gameManager.addPart("Unit"); gameManager.addPart("Tower"); System.out.println(gameManager); gameManager.updatePart("Part_0.Tower", "HP", "5000"); gameManager.updatePart("Part_0.Tower", "FireRate", "8"); gameManager.updatePart("Part_4.Unit", "Speed", "3"); System.out.println(gameManager); } }
package com.github.fhirschmann.clozegen.lib.annotators; import com.github.fhirschmann.clozegen.lib.type.GapAnnotation; import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.POS; import java.lang.reflect.Field; import java.util.Arrays; import java.util.Iterator; import java.util.logging.Level; import org.apache.log4j.Logger; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.cas.NonEmptyStringList; import org.uimafit.component.JCasAnnotator_ImplBase; import org.apache.uima.jcas.tcas.Annotation; import org.uimafit.util.FSCollectionFactory; /** * Base class for all gap generators. * <p> * A gap generator needs to be decorated with {@link GapGeneratorMetadata} and * specify the language it supports. Additionally, it can specify the POS * Subtag it wants to work on. For example, when generating gaps for articles, * one would use: * <pre> * @GapGeneratorMetadata(languageCode = "en", wantedPosSubtag = ART.class) * </pre> * </p> * * @author Fabian Hirschmann <fabian@hirschm.net> */ public abstract class AbstractGapGenerator extends JCasAnnotator_ImplBase { /** The logger (for all inheriting classes as well). */ protected final Logger log = Logger.getLogger(this.getClass()); /** The language code for an annotator. Needs to be set GapGeneratorMetadata. */ private String languageCode; /** The POS tags (Penn TreeBank Tags) the generator is working on. */ //protected String[] wantedPosTags = new String[] {}; /** The POS Subtag the generator is working on. */ private int wantedPosSubtag;; /** * Generates cloze tests item from validAnswers given subject. * * <p> * This method should generate a number of valid and invalid answers for a given * subject. For example, the subject "a" in the "articles" class might have "a" as * only valid answers and {"an","the"} as invalid answers. * </p> * * @param subject the word to generate validAnswers cloze test item for * @return valid and invalid answers for validAnswers gap */ public abstract Gap generate(Annotation subject); /** * Constructor which initializes the {@links GapGeneratorMetadata} annotator * using reflection. * */ public AbstractGapGenerator() { super(); for (java.lang.annotation.Annotation an : getClass().getAnnotations()) { if (an instanceof GapGeneratorMetadata) { final GapGeneratorMetadata md = (GapGeneratorMetadata) an; languageCode = md.languageCode(); // This block uses java reflection in order to allow the // annotation of generators. for (Field field : md.wantedPosSubtag().getDeclaredFields()) { if (field.getName().equals("type")) { try { wantedPosSubtag = field.getInt(md.wantedPosSubtag()); } catch (IllegalArgumentException ex) { wantedPosSubtag = POS.type; } catch (IllegalAccessException ex) { wantedPosSubtag = POS.type; } } } } } if (languageCode == null) { throw new NullPointerException( "Generator needs to be decorated with GapGeneratorMetadata!"); } } /** * Process the annotator. * * <p> * This method will set up the annotation for words in a word class (as defined by the * extending classes) and call generate() in the extending class for each word in this * class. * </p> * * @param jcas the CAS to work on * @throws AnalysisEngineProcessException on errors during engine execution */ @Override public final void process(final JCas jcas) throws AnalysisEngineProcessException { if (!languageCode.equals(jcas.getDocumentLanguage())) { log.error("This annotator is not made for your language!"); return; } for (final Iterator<Annotation> i = jcas.getAnnotationIndex( wantedPosSubtag).iterator(); i.hasNext();) { final Annotation subject = i.next(); //final POS pos = (POS) subject; //if (Arrays.asList(wantedTags).contains(pos.getPosValue())) { final GapAnnotation annotation = new GapAnnotation(jcas); annotation.setBegin(subject.getBegin()); annotation.setEnd(subject.getEnd()); final Gap gap = generate(subject); if (gap == null) { // Skip gap annotation if no gap was generated continue; } final NonEmptyStringList allAnswers = (NonEmptyStringList) FSCollectionFactory.createStringList( jcas, gap.getAllAnswers()); annotation.setAllAnswers(allAnswers); final NonEmptyStringList validAnswers = (NonEmptyStringList) FSCollectionFactory.createStringList( jcas, gap.getValidAnswers()); annotation.setValidAnswers(validAnswers); annotation.addToIndexes(); } } /** * @return the languageCode */ public String getLanguageCode() { return languageCode; } /** * @return the wantedPosSubtag */ public int getWantedPosSubtag() { return wantedPosSubtag; } }
package com.ochafik.lang.jnaerator; import static com.ochafik.lang.SyntaxUtils.as; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.classLiteral; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.expr; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.ident; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.memberRef; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.thisRef; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.cast; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.methodCall; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.staticField; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.thisField; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.typeRef; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.varRef; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ShortBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.TreeMap; import java.util.regex.Pattern; import org.rococoa.ObjCClass; import org.rococoa.ObjCObject; import org.rococoa.cocoa.foundation.NSObject; import org.bridj.FlagSet; import org.bridj.ValuedEnum; import org.bridj.SizeT; import org.bridj.ann.CLong; import org.bridj.ann.Ptr; import org.bridj.util.DefaultParameterizedType; import com.ochafik.lang.SyntaxUtils; import com.ochafik.lang.jnaerator.JNAeratorConfig.GenFeatures; import com.ochafik.lang.jnaerator.parser.Annotation; import com.ochafik.lang.jnaerator.parser.Arg; import com.ochafik.lang.jnaerator.parser.Declaration; import com.ochafik.lang.jnaerator.parser.Declarator; import com.ochafik.lang.jnaerator.parser.Define; import com.ochafik.lang.jnaerator.parser.Element; import com.ochafik.lang.jnaerator.parser.Enum; import com.ochafik.lang.jnaerator.parser.Expression; import com.ochafik.lang.jnaerator.parser.Function; import com.ochafik.lang.jnaerator.parser.Identifier; import com.ochafik.lang.jnaerator.parser.ModifiableElement; import com.ochafik.lang.jnaerator.parser.Modifier; import com.ochafik.lang.jnaerator.parser.ModifierType; import com.ochafik.lang.jnaerator.parser.ObjCppParser; import com.ochafik.lang.jnaerator.parser.Scanner; import com.ochafik.lang.jnaerator.parser.Struct; import com.ochafik.lang.jnaerator.parser.TypeRef; import com.ochafik.lang.jnaerator.parser.VariablesDeclaration; import com.ochafik.lang.jnaerator.parser.Declarator.ArrayDeclarator; import com.ochafik.lang.jnaerator.parser.Enum.EnumItem; import com.ochafik.lang.jnaerator.parser.Expression.AssignmentOp; import com.ochafik.lang.jnaerator.parser.Expression.AssignmentOperator; import com.ochafik.lang.jnaerator.parser.Expression.BinaryOp; import com.ochafik.lang.jnaerator.parser.Expression.BinaryOperator; import com.ochafik.lang.jnaerator.parser.Expression.Cast; import com.ochafik.lang.jnaerator.parser.Expression.Constant; import com.ochafik.lang.jnaerator.parser.Expression.EmptyArraySize; import com.ochafik.lang.jnaerator.parser.Expression.FunctionCall; import com.ochafik.lang.jnaerator.parser.Expression.MemberRef; import com.ochafik.lang.jnaerator.parser.Expression.MemberRefStyle; import com.ochafik.lang.jnaerator.parser.Expression.New; import com.ochafik.lang.jnaerator.parser.Expression.TypeRefExpression; import com.ochafik.lang.jnaerator.parser.Expression.UnaryOp; import com.ochafik.lang.jnaerator.parser.Expression.UnaryOperator; import com.ochafik.lang.jnaerator.parser.Expression.VariableRef; import com.ochafik.lang.jnaerator.parser.Identifier.QualifiedIdentifier; import com.ochafik.lang.jnaerator.parser.Identifier.SimpleIdentifier; import com.ochafik.lang.jnaerator.parser.StoredDeclarations.TypeDef; import com.ochafik.lang.jnaerator.parser.TypeRef.ArrayRef; import com.ochafik.lang.jnaerator.parser.TypeRef.FunctionSignature; import com.ochafik.lang.jnaerator.parser.TypeRef.Pointer; import com.ochafik.lang.jnaerator.parser.TypeRef.Primitive; import com.ochafik.lang.jnaerator.parser.TypeRef.SimpleTypeRef; import com.ochafik.lang.jnaerator.parser.TypeRef.TaggedTypeRef; import com.ochafik.lang.jnaerator.parser.TypeRef.TargettedTypeRef; import com.ochafik.lang.jnaerator.runtime.CGFloatByReference; import com.ochafik.lang.jnaerator.runtime.CharByReference; import com.ochafik.lang.jnaerator.runtime.NativeSize; import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; import com.ochafik.lang.jnaerator.runtime.globals.Global; import com.ochafik.lang.jnaerator.runtime.globals.GlobalByte; import com.ochafik.lang.jnaerator.runtime.globals.GlobalCGFloat; import com.ochafik.lang.jnaerator.runtime.globals.GlobalChar; import com.ochafik.lang.jnaerator.runtime.globals.GlobalDouble; import com.ochafik.lang.jnaerator.runtime.globals.GlobalFloat; import com.ochafik.lang.jnaerator.runtime.globals.GlobalInt; import com.ochafik.lang.jnaerator.runtime.globals.GlobalLong; import com.ochafik.lang.jnaerator.runtime.globals.GlobalNativeLong; import com.ochafik.lang.jnaerator.runtime.globals.GlobalNativeSize; import com.ochafik.lang.jnaerator.runtime.globals.GlobalShort; import com.ochafik.util.listenable.Pair; import com.ochafik.util.string.StringUtils; import com.sun.jna.Native; import com.sun.jna.WString; import com.sun.jna.ptr.ByReference; import com.sun.jna.ptr.ByteByReference; import com.sun.jna.ptr.DoubleByReference; import com.sun.jna.ptr.FloatByReference; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.LongByReference; import com.sun.jna.ptr.NativeLongByReference; import com.sun.jna.ptr.PointerByReference; import com.sun.jna.ptr.ShortByReference; public class TypeConversion implements ObjCppParser.ObjCParserHelper { Result result; public boolean allowUnknownPointers = true, allowFakePointers = false; public TypeConversion(Result result) { super(); this.result = result; initTypes(); } //public Set<Identifier> fakePointersSink; public enum TypeConversionMode { PrimitiveOrBufferParameter, NativeParameter, NativeParameterWithStructsPtrPtrs, FieldType, ReturnType, ExpressionType, StaticallySizedArrayField, PrimitiveReturnType, PointedValue } public Map<JavaPrim, Class<? extends ByReference>> primToByReference = new HashMap<JavaPrim, Class<? extends ByReference>>(); public Map<JavaPrim, Class<? extends Global>> primToGlobal = new HashMap<JavaPrim, Class<? extends Global>>(); public Map<JavaPrim, Class<? extends Buffer>> primToBuffer = new HashMap<JavaPrim, Class<? extends Buffer>>(); public final Set<String> byReferenceClassesNames = new HashSet<String>(); Map<String, JavaPrim> javaPrims = new TreeMap<String, JavaPrim>(); protected void prim(String from, JavaPrim to) { javaPrims.put(from, to); } public boolean isObjCppPrimitive(String s) { return javaPrims.containsKey(s); } public enum JavaPrim { Void(null, null, ESize.Zero), Char(Character.TYPE, Character.class, ESize.CharSize), Long(java.lang.Long.TYPE, java.lang.Long.class, ESize.Eight), Int(Integer.TYPE, Integer.class, ESize.Four), Short(java.lang.Short.TYPE, java.lang.Short.class, ESize.Two), Byte(java.lang.Byte.TYPE, java.lang.Byte.class, ESize.One), Boolean(java.lang.Boolean.TYPE, java.lang.Boolean.class, ESize.One), Float(java.lang.Float.TYPE, java.lang.Float.class, ESize.Four), Double(java.lang.Double.TYPE, java.lang.Double.class, ESize.Eight), NativeLong(com.sun.jna.NativeLong.class, com.sun.jna.NativeLong.class, ESize.StaticSizeField), NativeSize(NativeSize.class, NativeSize.class, ESize.StaticSizeField), NSInteger(org.rococoa.cocoa.foundation.NSInteger.class, org.rococoa.cocoa.foundation.NSInteger.class, ESize.StaticSizeField), NSUInteger(org.rococoa.cocoa.foundation.NSUInteger.class, org.rococoa.cocoa.foundation.NSUInteger.class, ESize.StaticSizeField), CGFloat(org.rococoa.cocoa.CGFloat.class, org.rococoa.cocoa.CGFloat.class, ESize.StaticSizeField); public final Class<?> type, wrapperType; public final String simpleName, name; public final boolean isPrimitive; public enum ESize { One(expr(1)), Two(expr(2)), Four(expr(4)), Eight(expr(8)), StaticSizeField(null) { @Override public Expression sizeof(JavaPrim p) { return staticField(p.type, "SIZE"); } }, CharSize(null) { @Override public Expression sizeof(JavaPrim p) { return staticField(Native.class, "WCHAR_SIZE"); } }, Zero(expr(0)); private final Expression sizeOfExpression; ESize(Expression sizeOfExpression) { this.sizeOfExpression = sizeOfExpression; } public Expression sizeof(JavaPrim p) { return sizeOfExpression.clone(); } } public final ESize size; private static Map<String, JavaPrim> nameToPrim; public static JavaPrim getJavaPrim(String name) { if (nameToPrim == null) { nameToPrim = new HashMap<String, JavaPrim>(); for (JavaPrim p : values()) { nameToPrim.put(p.simpleName, p); } } return nameToPrim.get(name); } JavaPrim(Class<?> type, Class<?> wrapperType, ESize size) { this.type = type; this.wrapperType = wrapperType; this.size = size; this.name = type == null ? "void" : type.getName(); this.isPrimitive = type == null || type.isPrimitive(); this.simpleName = type == null ? "void" : type.getSimpleName(); } } public Expression typeLiteral(TypeRef c) { if (c != null && c.toString().equals("?")) return new Constant(Constant.Type.Null, null); if (c instanceof SimpleTypeRef && result.config.runtime == JNAeratorConfig.Runtime.BridJ) { Identifier id = ((SimpleTypeRef) c).getName(); SimpleIdentifier sid = id.resolveLastSimpleIdentifier(); if (!sid.getTemplateArguments().isEmpty()) { Identifier erased = id.eraseTemplateArguments(); List<Expression> exprs = new ArrayList<Expression>(); exprs.add(typeLiteral(typeRef(erased.clone()))); for (Expression t : sid.getTemplateArguments()) { if (t instanceof Expression.TypeRefExpression) { exprs.add(typeLiteral(((Expression.TypeRefExpression) t).getType().clone())); } } return methodCall(expr(typeRef(DefaultParameterizedType.class)), "paramType", exprs.toArray(new Expression[exprs.size()])); } } return memberRef(expr(c), MemberRefStyle.Dot, "class"); } public void initTypes() { prim("void", JavaPrim.Void); prim("UTF32Char", JavaPrim.Char); prim("unichar", JavaPrim.Char); prim("int64_t", JavaPrim.Long); prim("uint64_t", JavaPrim.Long); prim("u_int64_t", JavaPrim.Long); prim("long long", JavaPrim.Long); prim("long long int", JavaPrim.Long); prim("long int", JavaPrim.Int); prim("LONGLONG", JavaPrim.Long); prim("ULONGLONG", JavaPrim.Long); prim("INT", JavaPrim.Int); prim("UINT", JavaPrim.Int); prim("SHORT", JavaPrim.Short); prim("USHORT", JavaPrim.Short); prim("BYTE", JavaPrim.Byte); prim("UBYTE", JavaPrim.Byte); prim("DOUBLE", JavaPrim.Double); prim("FLOAT", JavaPrim.Float); prim("WORD", JavaPrim.Short); prim("DWORD", JavaPrim.Int); if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) prim("BOOL", JavaPrim.Int); else prim("BOOL", JavaPrim.Boolean); prim("DWORD64", JavaPrim.Long); prim("LONG64", JavaPrim.Long); prim("UInt64", JavaPrim.Long); prim("SInt64", JavaPrim.Long); prim("__int64", JavaPrim.Long); prim("__int64_t", JavaPrim.Long); prim("int32_t", JavaPrim.Int); prim("uint32_t", JavaPrim.Int); prim("__int32_t", JavaPrim.Int); prim("__uint32_t", JavaPrim.Int); prim("u_int32_t", JavaPrim.Int); prim("uint32", JavaPrim.Int); prim("int32", JavaPrim.Int); prim("int", JavaPrim.Int); //prim("NSUInteger", JavaPrim.NativeSize); //prim("NSInteger", JavaPrim.NativeSize); prim("SInt32", JavaPrim.Int); prim("UInt32", JavaPrim.Int); prim("GLint", JavaPrim.Int); prim("GLuint", JavaPrim.Int); prim("GLenum", JavaPrim.Int); prim("GLsizei", JavaPrim.Int); prim("__darwin_size_t", JavaPrim.Int); prim("__int32", JavaPrim.Int); prim("NSInteger", JavaPrim.NSInteger); prim("NSUInteger", JavaPrim.NSUInteger); prim("CGFloat", JavaPrim.CGFloat); JavaPrim longPrim = result.config.gccLong ? JavaPrim.NativeSize : JavaPrim.NativeLong; prim("long", longPrim); prim("LONG", longPrim); prim("ULONG", longPrim); JavaPrim sizePrim = result.config.sizeAsLong ? longPrim : JavaPrim.NativeSize; prim("size_t", sizePrim); prim("ptrdiff_t", sizePrim); prim("int16_t", JavaPrim.Short); prim("uint16_t", JavaPrim.Short); prim("__int16_t", JavaPrim.Short); prim("__uint16_t", JavaPrim.Short); prim("u_int16_t", JavaPrim.Short); prim("uint16", JavaPrim.Short); prim("int16", JavaPrim.Short); prim("SInt16", JavaPrim.Short); prim("UInt16", JavaPrim.Short); prim("short", JavaPrim.Short); prim("WCHAR", JavaPrim.Short); prim("wchar_t", result.config.wcharAsShort ? JavaPrim.Short : JavaPrim.Char); prim("__int16", JavaPrim.Short); prim("int8_t", JavaPrim.Byte); prim("uint8_t", JavaPrim.Byte); prim("u_int8_t", JavaPrim.Byte); prim("__uint8_t", JavaPrim.Byte); prim("__int8_t", JavaPrim.Byte); prim("SInt8", JavaPrim.Byte); prim("UInt8", JavaPrim.Byte); prim("char", JavaPrim.Byte); prim("unsigned char", JavaPrim.Byte); prim("__unsigned char", JavaPrim.Byte); prim("signed char", JavaPrim.Byte); prim("__signed char", JavaPrim.Byte); prim("SignedByte", JavaPrim.Byte); prim("__int8", JavaPrim.Byte); prim("float", JavaPrim.Float); prim("NSFloat", JavaPrim.Float); prim("CGFloat", JavaPrim.Float); prim("double_t", JavaPrim.Double); prim("double", JavaPrim.Double); prim("NSDouble", JavaPrim.Double); prim("CGDouble", JavaPrim.Double); prim("bool", JavaPrim.Boolean); prim("Boolean", JavaPrim.Boolean); prim("boolean_t", JavaPrim.Boolean); primToByReference.put(JavaPrim.Int, IntByReference.class); primToByReference.put(JavaPrim.Char, CharByReference.class); primToByReference.put(JavaPrim.Short, ShortByReference.class); primToByReference.put(JavaPrim.Byte, ByteByReference.class); primToByReference.put(JavaPrim.Long, LongByReference.class); primToByReference.put(JavaPrim.Float, FloatByReference.class); primToByReference.put(JavaPrim.Double, DoubleByReference.class); primToByReference.put(JavaPrim.NativeLong, NativeLongByReference.class); primToByReference.put(JavaPrim.NativeSize, NativeSizeByReference.class); primToByReference.put(JavaPrim.NSInteger, NativeSizeByReference.class); primToByReference.put(JavaPrim.NSUInteger, NativeSizeByReference.class); primToByReference.put(JavaPrim.CGFloat, CGFloatByReference.class); //primsByReference.put(JavaPrim.Void, PointerByReference.class); for (Class<?> c : primToByReference.values()) { byReferenceClassesNames.add(c.getName()); } // byReferenceClassesNames.add(PointerByReference.class.getName()); primToGlobal.put(JavaPrim.Int, GlobalInt.class); primToGlobal.put(JavaPrim.Char, GlobalChar.class); primToGlobal.put(JavaPrim.Short, GlobalShort.class); primToGlobal.put(JavaPrim.Byte, GlobalByte.class); primToGlobal.put(JavaPrim.Long, GlobalLong.class); primToGlobal.put(JavaPrim.Float, GlobalFloat.class); primToGlobal.put(JavaPrim.Double, GlobalDouble.class); primToGlobal.put(JavaPrim.NativeLong, GlobalNativeLong.class); primToGlobal.put(JavaPrim.NativeSize, GlobalNativeSize.class); primToGlobal.put(JavaPrim.NSInteger, GlobalNativeSize.class); primToGlobal.put(JavaPrim.NSUInteger, GlobalNativeSize.class); primToGlobal.put(JavaPrim.CGFloat, GlobalCGFloat.class); primToBuffer.put(JavaPrim.Int, IntBuffer.class); primToBuffer.put(JavaPrim.Char, CharBuffer.class); primToBuffer.put(JavaPrim.Short, ShortBuffer.class); primToBuffer.put(JavaPrim.Byte, ByteBuffer.class); primToBuffer.put(JavaPrim.Long, LongBuffer.class); primToBuffer.put(JavaPrim.Float, FloatBuffer.class); primToBuffer.put(JavaPrim.Double, DoubleBuffer.class); //primToBuffer.put(JavaPrim.NativeLong, NativeLongByReference.class); } Map<String, TypeRef> manualTypeDefs = new HashMap<String, TypeRef>(); public Pair<TypeDef, Declarator> getTypeDef(Identifier name) { if (name == null) { return null; } Pair<TypeDef, Declarator> p = result.typeDefs.get(name); if (p == null) { return null; } Declarator value = p.getValue(); String rname = value == null ? null : value.resolveName(); if (rname != null) { if (name.equals("id")) { return null; } if (name.equals("SEL")) { return null; } if (name.equals("IMP")) { return null; } if (name.equals("Class")) { return null; } if (name.equals("BOOL")) { if (rname.equals("byte")) { return null; } } } return p; } public TypeRef resolveTypeDef(TypeRef valueType, final Identifier libraryClassName, final boolean convertToJavaRef, final boolean convertEnumToJavaRef) { if (valueType == null) { return null; } // if (valueType.toString().equals("CGFunctionEvaluateCallback")) // valueType = valueType; if (valueType instanceof TaggedTypeRef && convertToJavaRef) { TaggedTypeRef ttr = (TaggedTypeRef) valueType; if (ttr.getTag() != null) { TypeRef ref = ttr instanceof Struct ? typeRef(findStructRef(ttr.getTag(), libraryClassName)) : ttr instanceof Enum && convertEnumToJavaRef ? findEnum(ttr.getTag(), libraryClassName) : null; if (ref == null && convertEnumToJavaRef) { return ref; } } } final TypeRef valueTypeCl = valueType.clone(); Arg holder = new Arg(); holder.setValueType(valueTypeCl); valueTypeCl.accept(new Scanner() { java.util.Stack<String> names = new java.util.Stack<String>(); int depth = 0; @Override public void visitSimpleTypeRef(SimpleTypeRef simpleTypeRef) { depth++; try { Identifier name = ((SimpleTypeRef) simpleTypeRef).getName(); if (name == null) { return; } String nameStr = name.toString(); if (nameStr == null) { return; } if (JavaPrim.getJavaPrim(nameStr) != null) { return; } if (names.contains(nameStr)) { return; } names.push(nameStr); try { if (resolvesToPrimitive(nameStr)) { return; } super.visitSimpleTypeRef(simpleTypeRef); if (simpleTypeRef.isMarkedAsResolved()) { return; } // Identifier oc = findObjCClassIdent(name); // if (oc != null) { // name.replaceBy(oc); Pair<TypeDef, Declarator> p = getTypeDef(name); if (p != null) { TypeRef tr = p.getFirst().getValueType();//as(p.getSecond().mutateType(p.getFirst().getValueType()), TypeRef.class); if (tr instanceof Enum && !convertEnumToJavaRef) { simpleTypeRef.replaceBy(typeRef(int.class)); return; } if (tr instanceof TaggedTypeRef) { Identifier name2 = result.declarationsConverter.getActualTaggedTypeName((TaggedTypeRef) tr); if (name2 != null) { name = name2; } } if (convertToJavaRef) { if (tr instanceof TaggedTypeRef) { TaggedTypeRef s = (TaggedTypeRef) tr; if (s.isForwardDeclaration()) { return; } // if (tr instanceof Enum) { // tr = typeRef(s.getTag().clone()); // } else { Identifier ident = result.getTaggedTypeIdentifierInJava(s); if (ident != null) { tr = typeRef(ident);//findRef(name, s, libraryClassName)); } } else if (tr instanceof FunctionSignature) { tr = findCallbackRef((FunctionSignature) tr, libraryClassName); } } String strs = simpleTypeRef.toString(); String trs = tr == null ? null : tr.toString(); if (trs != null && !strs.equals(trs)) { TypeRef clo = tr.clone(); simpleTypeRef.replaceBy(clo); if (depth < 30) { clo.accept(this); } else { System.err.println("Infinite loop in type conversion ? " + tr); } } return; } TypeRef manualTypeRef = manualTypeDefs.get(name); if (manualTypeRef != null) { if (!convertToJavaRef) { return; } simpleTypeRef.replaceBy(manualTypeRef); return; } TypeRef structRef = typeRef(result.typeConverter.findStructRef(name, libraryClassName)); if (structRef != null) { if (!convertToJavaRef) { return; } simpleTypeRef.replaceBy(structRef); } TypeRef enumRef = result.typeConverter.findEnum(name, libraryClassName); if (enumRef != null) { if (!convertToJavaRef || !convertEnumToJavaRef) { return; } simpleTypeRef.replaceBy(enumRef); } Define define = result.defines.get(name); Expression expression = define == null ? null : define.getValue(); if (expression != null) { if (!convertToJavaRef) { return; } Identifier fieldName = null; if (expression instanceof Expression.VariableRef) { fieldName = ((Expression.VariableRef) expression).getName(); } else if (expression instanceof MemberRef) { fieldName = ((MemberRef) expression).getName(); } if (fieldName != null && !fieldName.equals(name)) { simpleTypeRef.replaceBy(resolveTypeDef(new TypeRef.SimpleTypeRef(fieldName), libraryClassName, true /*convertToJavaRef*/, convertEnumToJavaRef)); return; } } } finally { names.pop(); } } finally { depth } } }); TypeRef tr = holder.getValueType(); // tr.setParentElement(valueType.getParentElement()); return tr;// == null ? null : tr.clone(); } public boolean resolvesToPrimitive(String name) { return javaPrims.containsKey(name); } // TypeRef getPrimitiveRef(TypeRef valueType, String callerLibraryClass) { // JavaPrim prim = getPrimitive(valueType, callerLibraryClass); // if (prim == null) // return null; // TypeRef tr = typeRef(prim); // if (valueType.isUnsigned()) // tr.addAnnotation(new Annotation(Unsigned.class)); // if (valueType.isUnsigned()) // tr.addAnnotation(new Annotation(Unsigned.class)); // return tr; public static class JavaPrimitive extends Primitive { JavaPrim javaPrim; public JavaPrimitive() { } public JavaPrimitive(JavaPrim javaPrim) { super(); setName(ident(javaPrim == JavaPrim.Void ? Void.TYPE : javaPrim.type)); this.javaPrim = javaPrim; } public JavaPrim getJavaPrim() { return javaPrim; } public void setJavaPrim(JavaPrim javaPrim) { this.javaPrim = javaPrim; } } public JavaPrim getPrimitive(TypeRef valueType, Identifier libraryClassName) { valueType = resolveTypeDef(valueType, libraryClassName, true, true); if (valueType == null) { return null; } Identifier name = null; List<Modifier> mods = valueType.getModifiers(); int longCount = ModifierType.Long.countIn(mods); if (valueType instanceof JavaPrimitive) { return ((JavaPrimitive) valueType).getJavaPrim(); } if (valueType instanceof Primitive) { name = ((Primitive) valueType).getName(); if (name == null) { if (longCount == 1) { name = ident("long"); } else if (longCount > 1) { name = ident("long long"); } else if (valueType.hasModifier(ModifierType.Short)) { name = ident("short"); } else { name = ident("int"); } } } else if (valueType instanceof SimpleTypeRef) { name = ((SimpleTypeRef) valueType).getName(); } if (name == null) { return null; } JavaPrim p = JavaPrim.getJavaPrim(name.toString()); if (p != null && !p.isPrimitive) { return p; } boolean isLong = false; String str; if ((isLong = valueType.getModifiers().contains("long")) || valueType.getModifiers().contains("short")) { str = (isLong ? "long " : "short ") + name; } else { str = name.toString(); } JavaPrim type = javaPrims.get(str); if (type == JavaPrim.Int && longCount > 1) { return JavaPrim.Long; } return type; } public Identifier findStructRef(Identifier name, Identifier libraryClassName) { return findStructRef(result.structsByName.get(name), name, libraryClassName); } public Identifier findStructRef(Struct s, Identifier name, Identifier libraryClassName) { if (s == null || s.isForwardDeclaration()) { Pair<TypeDef, Declarator> pair = getTypeDef(name); if (pair == null) { return null; } if (pair.getFirst() == null || pair.getSecond() == null) { return null; } Object td = pair.getSecond().mutateType(pair.getFirst().getValueType()); if (!(td instanceof Struct)) { return null; } s = (Struct) td; } if (s == null && result.config.runtime == JNAeratorConfig.Runtime.BridJ) { String ns = name.toString(); Class<?> cl = null; if (ns.equals("IUnknown")) cl = org.bridj.cpp.com.IUnknown.class; else if (ns.equals("GUID")) cl = org.bridj.cpp.com.GUID.class; else if (ns.equals("RECT")) cl = org.bridj.cpp.com.RECT.class; if (cl != null) return ident(cl); } return result.getTaggedTypeIdentifierInJava(s); /* name = result.declarationsConverter.getActualTaggedTypeName((TaggedTypeRef) pair.getFirst().getValueType()); return findRef(name, s, libraryClassName, !result.config.putTopStructsInSeparateFiles); } else { return result.getTaggedTypeIdentifierInJava(s); //name = result.declarationsConverter.getActualTaggedTypeName(s); }*/ } public Identifier findStructRef(Struct s, Identifier libraryClassName) { switch (s.getType()) { case ObjCClass: case ObjCProtocol: return result.objectiveCGenerator.getFullClassName(s); default: return findStructRef(s, result.declarationsConverter.getActualTaggedTypeName(s), libraryClassName); } } // public String find(String name, Element e, String callerLibraryClass) { // if (e == null) // return null; // String library = result.getLibrary(e); // if (library == null) // return null; // SimpleIdentifier libClass = result.getLibraryClassFullName(library); // return SyntaxUtils.equal(libClass, callerLibraryClass) ? name : libClass + "." + name; public Identifier libMember(Identifier libClass, Identifier libraryClassName, Identifier member) { //return ident(SyntaxUtils.equal(libClass, libraryClassName) ? null : libClass, member); return ident(libClass, member); //return member; //TODODODODODODODODOoOOOOO } public Identifier findRef(Identifier name, Element e, Identifier libraryClassName, boolean inLibClass) { if (e == null || !name.isPlain()) { return null; } String library = result.getLibrary(e); if (library == null) { return null; } // e = e.getParentElement(); Struct parentStruct = e instanceof Struct ? (Struct) e : e.findParentOfType(Struct.class); if (!inLibClass && parentStruct != null) { if (parentStruct == e) { return ident(result.getLibraryPackage(library), name); } return ident(result.getTaggedTypeIdentifierInJava(parentStruct), name); } return libMember(result.getLibraryClassFullName(library), libraryClassName, name); } public SimpleTypeRef findEnum(Identifier name, Identifier libraryClassName) { Enum s = result.enumsByName.get(name); if (s == null) { return null; } return findEnumRef(s, libraryClassName); } public SimpleTypeRef findEnumRef(Enum s, Identifier libraryClassName) { if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) return typeRef(result.getTaggedTypeIdentifierInJava(s)); Identifier name = result.declarationsConverter.getActualTaggedTypeName(s); String library = result.getLibrary(s); if (library == null) { return null; } Identifier libClass = result.getLibraryClassFullName(library); //return new SimpleTypeRef(SyntaxUtils.equal(libClass, callerLibraryClass) ? name : libClass + "." + name); /*if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) { return typeRef(findRef(name, s, libraryClassName, result.config.putTopStructsInSeparateFiles)); }*/ SimpleTypeRef tr = new SimpleTypeRef("int"); if (result.config.features.contains(JNAeratorConfig.GenFeatures.EnumTypeLocationComments)) { tr.setCommentBefore("@see " + (SyntaxUtils.equal(libClass, libraryClassName) ? name : libClass + "#" + name)); } // if (s.getTag() != null) // tr.setCommentBefore("@see enums in " + s.getTag()); return tr; } public static Expression javaStaticFieldRef(Identifier javaClass, Identifier fieldName) { return memberRef( expr(typeRef(javaClass)), MemberRefStyle.Dot, fieldName); } public Expression findDefine(Identifier name) { Define s = result.defines.get(name); String library = s == null ? null : result.getLibrary(s); return library == null ? null : javaStaticFieldRef(result.getLibraryClassFullName(library), name); } public Identifier inferCallBackName(FunctionSignature functionSignature, boolean prependNamespaces, boolean qualify, Identifier libraryClassName) { List<String> nameElements = new ArrayList<String>(); Identifier name = functionSignature.getFunction().getName(); if (name != null) { name = name.clone(); } Identifier parentIdent = null; Element parent = functionSignature.getParentElement(); boolean firstParent = true; while (parent != null) { if (parent instanceof Struct) { parentIdent = findStructRef((Struct) parent, null); break; } else if (firstParent) { if (name == null && parent instanceof TypeDef) { Declarator simpleSto = null; for (Declarator sto : ((TypeDef) parent).getDeclarators()) { String stoName = sto.resolveName(); if (stoName == null) { continue; } if (!(sto instanceof ArrayDeclarator)) { boolean weirdName = stoName.startsWith("_") || stoName.endsWith("_"); if (simpleSto == null || (simpleSto.resolveName().startsWith("_") || simpleSto.resolveName().endsWith("_")) && !weirdName) { simpleSto = sto; } if (!weirdName) { break; } } if (stoName != null) { name = new SimpleIdentifier(stoName); } } } else if (name == null && parent instanceof Arg) { Arg arg = (Arg) parent; Function f = SyntaxUtils.as(arg.getParentElement(), Function.class); if (f != null) { name = new SimpleIdentifier(f.getName() + "_" + arg.getName()); break; } } else if (firstParent) { // if (//parent instanceof VariablesDeclaration || // parent instanceof FunctionPointerDeclaration // //|| parent instanceof TypeDef // nameElements.add("Callback"); } } parent = parent.getParentElement(); firstParent = false; } if (qualify && parentIdent == null) { //if (libraryClassName != null) // parentIdent = libraryClassName; //else { String library = result.getLibrary(functionSignature); if (library != null) { parentIdent = result.getLibraryClassFullName(library); } } if (prependNamespaces) { if (name == null) { name = new SimpleIdentifier("callback"); } nameElements.add(name.toString()); return ident(qualify ? parentIdent : null, StringUtils.implode(nameElements, "_")); } else { return ident(qualify ? parentIdent : null, name); } } public TypeRef findCallbackRef(Identifier name, Identifier libraryClassName) { FunctionSignature s = result.callbacksByName.get(name); if (s == null) { return null; } // Struct parentStruct = s.findParentOfType(Struct.class); // if (parentStruct != null && (parentStruct.getType() == Struct.Type.ObjCClass || parentStruct.getType() == Struct.Type.ObjCProtocol)) { // //Identifier structName = result.declarationsConverter.getActualTaggedTypeName(parentStruct); // return //result.result.getObjCClass(parentStruct.getName()). // typeRef(//libMember(structName, libraryClassName, // inferCallBackName(s, true, true)//) return findCallbackRef(s, libraryClassName); } public TypeRef findCallbackRef(FunctionSignature s, Identifier callerLibraryClass) { String library = result.getLibrary(s); if (library == null) { return null; } // Struct parentStruct = s.findParentOfType(Struct.class); // if (parentStruct != null && (parentStruct.getType() == Struct.Type.ObjCClass || parentStruct.getType() == Struct.Type.ObjCProtocol)) { // Identifier structName = result.declarationsConverter.getActualTaggedTypeName(parentStruct); // return // typeRef(ident(structName, inferCallBackName(s, true, true))); return typeRef(inferCallBackName(s, true, true, callerLibraryClass)); // return typeRef(libMember(result.getLibraryClassFullName(library), callerLibraryClass, inferCallBackName(s, true, true))); //typeRef(ident(result.getLibraryClassFullName(library), inferCallBackName(s, true))); } static TypeRef primRef(JavaPrim p) { if (p == null) { return null; } return new JavaPrimitive(p); // return new SimpleTypeRef(toString(p)); } boolean isResolved(SimpleTypeRef tr) { return tr != null && (tr.isMarkedAsResolved() || isResolved(tr.getName())); } boolean isResolved(Identifier i) { if (i == null || i.isPlain()) { return false; } return (i instanceof Identifier.QualifiedIdentifier) && Identifier.QualificationSeparator.Dot.equals(((Identifier.QualifiedIdentifier) i).getSeparator()); } public enum ConvType { Enum, Pointer, Primitive, Struct, NativeLong, NativeSize, Void, Callback } public class NL4JConversion { public ConvType type; public TypeRef typeRef, indirectType; public List<Expression> arrayLengths; public Expression bits; public Expression getExpr, setExpr; public boolean wideString, readOnly, isPtr, byValue, nativeSize, cLong, isUndefined; public Charset charset; public final List<Annotation> annotations = new ArrayList<Annotation>(); //public String structIOFieldGetterNameRadix; public String pointerFieldGetterNameRadix; public Expression arrayLength() { Expression length = null; for (Expression m : arrayLengths) { m.setParenthesis(true); if (length == null) length = m.clone(); else length = expr(length, BinaryOperator.Multiply, m.clone()); } return length.setParenthesis(arrayLengths.size() > 1); } public TypeRef getIndirectTypeRef() { if (type == ConvType.Void) { return typeRef(ident("?")); } if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) { if (type == ConvType.NativeSize) { return typeRef(SizeT.class); } if (type == ConvType.NativeLong) { return typeRef(org.bridj.CLong.class); } } TypeRef t = indirectType == null ? typeRef : indirectType; return t == null ? null : t.clone(); } public <M extends ModifiableElement> M annotateRawType(M element) throws UnsupportedConversionException { element.addAnnotations(annotations); if (type != null) { switch (type) { case Enum: case Primitive: case Void: break; case NativeLong: element.addAnnotation(new Annotation(CLong.class)); break; case NativeSize: element.addAnnotation(new Annotation(Ptr.class)); break; case Pointer: element.addAnnotation(new Annotation(Ptr.class)); break; case Struct: //throw new UnsupportedConversionException(typeRef, "Struct by value not supported yet"); break; default: throw new UnsupportedConversionException(typeRef, "Not supported"); } } return element; } public <M extends ModifiableElement> M annotateTypedType(M element) throws UnsupportedConversionException { element.addAnnotations(annotations); if (type != ConvType.Pointer) { annotateRawType(element); } return element; } } static Map<String, Pair<Integer, Class<?>>> buffersAndArityByType = new HashMap<String, Pair<Integer, Class<?>>>(); static Map<String, Pair<Integer, Class<?>>> arraysAndArityByType = new HashMap<String, Pair<Integer, Class<?>>>(); static Map<String, String> pointerFieldGetterNameRadixByType = new HashMap<String, String>(); static { Object[] data = new Object[]{ "char", Byte.TYPE, byte[].class, ByteBuffer.class, "Char", "long", Long.TYPE, long[].class, LongBuffer.class, "Long", "int", Integer.TYPE, int[].class, IntBuffer.class, "Int", "short", Short.TYPE, short[].class, ShortBuffer.class, "Short", "wchar_t", Character.TYPE, char[].class, CharBuffer.class, "WChar", "double", Double.TYPE, double[].class, DoubleBuffer.class, "Double", "float", Float.TYPE, float[].class, FloatBuffer.class, "Float", "bool", Boolean.TYPE, boolean[].class, null, "Bool" }; for (int arity : new int[]{1, 2, 4, 8, 16}) { String suffix = arity == 1 ? "" : arity + ""; for (int i = 0; i < data.length; i += 5) { String rawType = (String) data[i]; Class<?> scalClass = (Class<?>) data[i + 1]; Class<?> arrClass = (Class<?>) data[i + 2]; Class<?> buffClass = (Class<?>) data[i + 3]; String radix = (String) data[i + 4]; Pair<Integer, Class<?>> buffPair = new Pair<Integer, Class<?>>(arity, arity == 1 ? scalClass : buffClass), arrPair = new Pair<Integer, Class<?>>(arity, arity == 1 ? scalClass : arrClass); for (String type : new String[]{rawType + suffix, "u" + rawType + suffix}) { buffersAndArityByType.put(type, buffPair); arraysAndArityByType.put(type, arrPair); pointerFieldGetterNameRadixByType.put(type, radix); } } } } public NL4JConversion convertTypeToNL4J(TypeRef valueType, Identifier libraryClassName, Expression structIOExpr, Expression valueExpr, int fieldIndex, int bits) throws UnsupportedConversionException { TypeRef original = valueType; //if (valueType != null && valueType.toString().contains("MonoDomain")) // valueType = (TypeRef)valueType; valueType = resolveTypeDef(valueType, libraryClassName, true, true); //Expression offsetExpr = structIOExpr == null ? null : methodCall(structIOExpr, "getFieldOffset", expr(fieldIndex)); //Expression bitOffsetExpr = structIOExpr == null || bits <= 0 ? null : methodCall(structIOExpr, "getFieldBitOffset", expr(fieldIndex)); //Expression bitLengthExpr = structIOExpr == null || bits <= 0 ? null : methodCall(structIOExpr, "getFieldBitLength", expr(fieldIndex)); NL4JConversion conv = new NL4JConversion(); if (valueType == null) { conv.type = ConvType.Void; conv.typeRef = primRef(JavaPrim.Void); return conv; } //if (valueType instanceof Struct) // valueType = typeRef(findStructRef((Struct)valueType, libraryClassName)); if (valueType instanceof TargettedTypeRef) { TypeRef targetRef = ((TargettedTypeRef) valueType).getTarget(); if (valueType instanceof Pointer.ArrayRef) { Pointer.ArrayRef arrayRef = (Pointer.ArrayRef) valueType; List<Expression> sizes = new ArrayList<Expression>(); for (Expression dim : arrayRef.flattenDimensions()) { if (dim == null || dim instanceof EmptyArraySize) continue; Expression m = result.typeConverter.convertExpressionToJava(dim, libraryClassName, false).getFirst(); m.setParenthesis(false); sizes.add(m); } if (!sizes.isEmpty()) conv.arrayLengths = sizes; } try { NL4JConversion targetConv = convertTypeToNL4J(targetRef, libraryClassName, null, null, -1, -1); //if (result.isFakePointer(libraryClassName)) if (targetConv.isUndefined && allowFakePointers && original instanceof SimpleTypeRef) { conv.isPtr = true; conv.type = ConvType.Pointer; conv.typeRef = typeRef(result.getFakePointer(libraryClassName, ((SimpleTypeRef)original).getName().clone())); if (structIOExpr != null) { if (conv.arrayLengths == null) conv.setExpr = methodCall(structIOExpr.clone(), "setPointerField", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr.clone(), "getTypedPointerField", thisRef(), expr(fieldIndex)); } return conv; } TypeRef pointedTypeRef = targetConv.getIndirectTypeRef(); if (targetConv.type != ConvType.Void) { if (targetConv.type == ConvType.NativeSize) pointedTypeRef = typeRef(SizeT.class); else if (targetConv.type == ConvType.NativeLong) pointedTypeRef = typeRef(CLong.class); } if (pointedTypeRef != null) { conv.isPtr = true; conv.type = ConvType.Pointer; conv.typeRef = typeRef(ident(result.config.runtime.pointerClass, expr(pointedTypeRef.clone()))); if (structIOExpr != null) { if (conv.arrayLengths == null) conv.setExpr = methodCall(structIOExpr.clone(), "setPointerField", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr.clone(), "getPointerField", thisRef(), expr(fieldIndex)); } return conv; } } catch (UnsupportedConversionException ex) { conv.isPtr = true; conv.type = ConvType.Pointer; conv.typeRef = typeRef(result.config.runtime.pointerClass); return conv; }//*/ /*if (valueType instanceof TypeRef.Pointer && targetRef instanceof SimpleTypeRef && allowFakePointers) { conv.typeRef = typeRef(ident(result.config.runtime.pointerClass, expr(typeRef(result.getUndefinedType(libraryClassName, ((SimpleTypeRef)targetRef).getName().clone()))))); if (structIOExpr != null) { if (conv.arrayLengths == null) conv.setExpr = methodCall(structIOExpr.clone(), "setPointerField", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr.clone(), "getTypedPointerField", thisRef(), expr(fieldIndex)); } return conv; }*/ } } else {//if (valueType instanceof SimpleTypeRef || valueType instanceof TaggedTypeRef || valueType) { JavaPrim prim = getPrimitive(valueType, libraryClassName); if (prim != null) { String radix; switch (prim) { case NativeLong: conv.type = ConvType.NativeLong; conv.typeRef = typeRef(Long.TYPE); conv.indirectType = typeRef(org.bridj.CLong.class); radix = "CLong"; break; case NativeSize: conv.type = ConvType.NativeSize; conv.typeRef = typeRef(Long.TYPE); conv.indirectType = typeRef(org.bridj.SizeT.class); radix = "SizeT"; break; case Void: conv.type = ConvType.Void; conv.typeRef = primRef(prim); radix = null; break; default: conv.type = ConvType.Primitive; conv.typeRef = primRef(prim); conv.indirectType = typeRef(prim.wrapperType); radix = StringUtils.capitalize(prim.type.getName()); break; } if (structIOExpr != null && radix != null) { conv.setExpr = methodCall(structIOExpr.clone(), "set" + radix + "Field", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr.clone(), "get" + radix + "Field", thisRef(), expr(fieldIndex)); } return conv; } else { Identifier valueName = valueType instanceof SimpleTypeRef ? ((SimpleTypeRef)valueType).getName() : null; // Structs if (valueType instanceof Struct) conv.typeRef = typeRef(findStructRef((Struct)valueType, libraryClassName)); else if (result.structsFullNames.contains(valueName)) conv.typeRef = valueType; else conv.typeRef = typeRef(findStructRef(valueName, libraryClassName)); if (conv.typeRef != null) { //conv.setExpr = methodCall(structPeerExpr.clone(), "set" + radix, offsetExpr.clone(), valueExpr); if (structIOExpr != null) { conv.getExpr = methodCall(structIOExpr, "getNativeObjectField", thisRef(), expr(fieldIndex)); //conv.getExpr = new Expression.New(conv.typeRef, (Expression)methodCall(structIOExpr.clone(), "offset", offsetExpr.clone())); } conv.type = ConvType.Struct; return conv; } // Enums if (valueType instanceof Enum) conv.typeRef = findEnumRef((Enum)valueType, libraryClassName); else if (result.enumsFullNames.contains(valueName)) conv.typeRef = valueType; else conv.typeRef = findEnum(valueName, libraryClassName); if (conv.typeRef != null) { if (structIOExpr != null) { conv.setExpr = methodCall(structIOExpr, "setEnumField", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr, "getEnumField", thisRef(), expr(fieldIndex));//expr(typeRef(FlagSet.class)), "fromValue", methodCall(structPeerExpr.clone(), "getInt", expr(fieldIndex)), classLiteral(conv.typeRef.clone())); } conv.type = ConvType.Enum; conv.typeRef = typeRef(ident(ValuedEnum.class, expr(conv.typeRef))); return conv; } // Callbacks conv.typeRef = conv.typeRef = result.callbacksFullNames.contains(valueName) ? valueType : valueType instanceof FunctionSignature ? findCallbackRef((FunctionSignature)valueType, libraryClassName) : findCallbackRef(valueName, libraryClassName); if (conv.typeRef != null) { if (structIOExpr != null) { conv.setExpr = methodCall(structIOExpr.clone(), "setPointerField", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr.clone(), "getPointerField", thisRef(), expr(fieldIndex)); } conv.type = ConvType.Pointer; conv.typeRef = typeRef(ident(result.config.runtime.pointerClass, expr(conv.typeRef))); return conv; } } } if (valueType instanceof SimpleTypeRef && allowFakePointers) { conv.typeRef = typeRef(result.getUndefinedType(libraryClassName, ((SimpleTypeRef)valueType).getName().clone())); conv.isUndefined = true; return conv; } throw new UnsupportedConversionException(original, "Unsupported type"); } @SuppressWarnings("unchecked") Pair<TypeRef, List<Annotation>> toRawNL4JType(TypeRef nl4jType) throws UnsupportedConversionException { if (!(nl4jType instanceof SimpleTypeRef)) { throw new UnsupportedConversionException(nl4jType, "Not a known type : " + nl4jType); } Pair<TypeRef, List<Annotation>> ret = new Pair<TypeRef, List<Annotation>>(nl4jType.clone(), Collections.EMPTY_LIST); if (nl4jType instanceof TypeRef.Primitive) { return ret; } SimpleTypeRef str = (SimpleTypeRef) nl4jType; Identifier strn = str.getName(); if (strn.equals(result.config.runtime.pointerClass.getName())) { ret.setSecond(Arrays.asList(new Annotation(Ptr.class))); ret.setFirst(typeRef(JavaPrim.Long.type)); } else if (strn.equals(ValuedEnum.class.getName())) { ret.setFirst(typeRef(JavaPrim.Int.type)); } else { throw new UnsupportedConversionException(nl4jType, "No raw conversion available yet for type " + nl4jType); } return ret; } /* public static class NL4JTypeConversion { public enum Type { Enum, Pointer, Primitive, Struct, NativeLong, NativeSize, Void, Callback } public NL4JTypeConversion(TypeRef directType, TypeRef indirectType, Type type) { this.directType = directType; this.indirectType = indirectType; this.type = type; } private final TypeRef directType, indirectType; public final Type type; public <M extends ModifiableElement> M annotateRawType(M element) throws UnsupportedConversionException { if (type != null) switch (type) { case Enum: case Primitive: case Void: break; case NativeLong: element.addAnnotation(new Annotation(CLong.class)); break; case NativeSize: element.addAnnotation(new Annotation(Ptr.class)); break; case Pointer: element.addAnnotation(new Annotation(Ptr.class)); break; case Struct: throw new UnsupportedConversionException(directType, "Struct by value not supported yet"); default: throw new UnsupportedConversionException(directType, "Not supported"); } return element; } public <M extends ModifiableElement> M annotateTypedType(M element) throws UnsupportedConversionException { if (type != Type.Pointer) annotateRawType(element); return element; } public TypeRef getTypedTypeRef() { return directType == null ? typeRef("void") : directType.clone(); } public TypeRef getIndirectTypeRef() { if (type == NL4JTypeConversion.Type.Void) return typeRef(ident("?")); TypeRef t = indirectType == null ? directType : indirectType; return t == null ? null : t.clone(); } public TypeRef getRawType() throws UnsupportedConversionException { if (type == null) { return directType.clone(); } switch (type) { case Enum: return typeRef(Integer.TYPE); case Pointer: return typeRef(Long.TYPE); case Void: return typeRef("void"); case Primitive: case NativeLong: case NativeSize: return getTypedTypeRef(); case Struct: throw new UnsupportedConversionException(getTypedTypeRef(), "Struct by value not supported yet"); default: throw new UnsupportedConversionException(getTypedTypeRef(), "Not supported"); } } } NL4JTypeConversion toNL4JType(TypeRef valueType, java.util.Stack<String> namesStack, Identifier library) throws UnsupportedConversionException { if (valueType instanceof TargettedTypeRef) { TargettedTypeRef ttr = (TargettedTypeRef)valueType; NL4JTypeConversion targetConv = toNL4JType(ttr.getTarget(), namesStack, library); TypeRef pointedTypeRef = targetConv.getIndirectTypeRef(); if (targetConv.type != NL4JTypeConversion.Type.Void) { try { if (targetConv.type == NL4JTypeConversion.Type.NativeSize) pointedTypeRef = typeRef(SizeT.class); else if (targetConv.type == NL4JTypeConversion.Type.NativeLong) pointedTypeRef = typeRef(CLong.class); else { String s = targetConv.getRawType().toString(); if (s.equals(Byte.TYPE.getName()) && (result.config.charPtrAsString || valueType.hasModifier(ModifierType.__const))) return new NL4JTypeConversion( typeRef(ident(result.config.runtime.pointerClass, expr(typeRef(String.class)))), null, NL4JTypeConversion.Type.Pointer ); } } catch (UnsupportedConversionException ex) { } } return new NL4JTypeConversion( typeRef( ident( result.config.runtime.pointerClass, expr(pointedTypeRef) ) ), null, NL4JTypeConversion.Type.Pointer ); } if (valueType instanceof SimpleTypeRef) { JavaPrim prim = getPrimitive(valueType, null); if (prim != null) { switch (prim) { case NativeLong: return new NL4JTypeConversion(typeRef(Long.TYPE), typeRef(Long.class), NL4JTypeConversion.Type.NativeLong); case NativeSize: return new NL4JTypeConversion(typeRef(Long.TYPE), typeRef(Long.class), NL4JTypeConversion.Type.NativeSize); case Void: return new NL4JTypeConversion(null, null, NL4JTypeConversion.Type.Void); default: return new NL4JTypeConversion(typeRef(prim.type), typeRef(prim.wrapperType), NL4JTypeConversion.Type.Primitive); } } Identifier name = ((SimpleTypeRef)valueType).getName(); if (name == null) return null; if (namesStack == null) namesStack = new Stack<String>(); String nameStr = name.toString(); if (nameStr == null || namesStack.contains(nameStr)) return null; namesStack.push(nameStr); try { Pair<TypeDef,Declarator> p = getTypeDef(name); if (p != null) { TypeRef tr = p.getFirst().getValueType();//as(p.getSecond().mutateType(p.getFirst().getValueType()), TypeRef.class); if (tr instanceof TaggedTypeRef) { TaggedTypeRef ttr = (TaggedTypeRef)tr; Identifier name2 = result.declarationsConverter.getActualTaggedTypeName(ttr); if (name2 != null) { name = name2; nameStr = name.toString(); } //if (ttr.isForwardDeclaration()) // return; TypeRef javaRef = typeRef(result.getTaggedTypeIdentifierInJava(ttr)); if (tr instanceof Enum) { return new NL4JTypeConversion(toNL4JEnum(javaRef), null, NL4JTypeConversion.Type.Enum); } else if (tr instanceof Struct) { return new NL4JTypeConversion(javaRef, null, NL4JTypeConversion.Type.Struct); } } else if (tr instanceof FunctionSignature) { return new NL4JTypeConversion(typeRef(ident(result.config.runtime.pointerClass, expr(findCallbackRef((FunctionSignature)tr, null)))), null, NL4JTypeConversion.Type.Pointer); } else { String strs = valueType.toString(); String trs = tr == null ? null : tr.toString(); if (trs != null && !strs.equals(trs)) { try { TypeRef clo = tr.clone(); return toNL4JType(clo, namesStack, library); } catch (UnsupportedConversionException ex) { if (tr instanceof TypeRef.Pointer && allowFakePointers) { return new NL4JTypeConversion( typeRef(result.getFakePointer(library, name.clone())), null, null ); } else throw ex; } } } } TypeRef manualTypeRef = manualTypeDefs.get(nameStr); if (manualTypeRef != null) return toNL4JType(manualTypeRef, namesStack, library); TypeRef structRef = typeRef(findStructRef(name, null)); if (structRef != null) { return new NL4JTypeConversion(structRef.clone(), null, NL4JTypeConversion.Type.Struct); } TypeRef enumRef = findEnum(name, null); if (enumRef != null) { return new NL4JTypeConversion(toNL4JEnum(enumRef), null, NL4JTypeConversion.Type.Enum); } Define define = result.defines.get(nameStr); Expression expression = define == null ? null : define.getValue(); if (expression != null) { Identifier fieldName = null; if (expression instanceof Expression.VariableRef) fieldName = ((Expression.VariableRef) expression).getName(); else if (expression instanceof MemberRef) fieldName = ((MemberRef) expression).getName(); if (fieldName != null && !fieldName.equals(name)) return toNL4JType(new TypeRef.SimpleTypeRef(fieldName), namesStack, library); } } finally { namesStack.pop(); } } throw new UnsupportedConversionException(valueType, "Unsupported type"); } TypeRef toNL4JEnum(TypeRef enumResolvedJavaRef) { return typeRef(ident(ValuedEnum.class, expr(enumResolvedJavaRef.clone()))); } */ public Expression getFlatArraySizeExpression(Pointer.ArrayRef arrayRef, Identifier callerLibraryName) throws UnsupportedConversionException { Expression mul = null; List<Expression> dims = arrayRef.flattenDimensions(); for (int i = dims.size(); i Expression x = dims.get(i); if (x == null || x instanceof EmptyArraySize) { return null; //javaType = jr = new ArrayRef(typeRef(Pointer.class)); //break; } else { Pair<Expression, TypeRef> c = result.typeConverter.convertExpressionToJava(x, callerLibraryName, false); c.getFirst().setParenthesis(dims.size() > 1); if (mul == null) { mul = c.getFirst(); } else { mul = expr(c.getFirst(), BinaryOperator.Multiply, mul); } } } return mul; } Pattern wstringPat = Pattern.compile("(__)?const wchar_t\\*"), stringPat = Pattern.compile("(__)?const char\\*"), wstringPtrPtrPat = Pattern.compile("(__)?const wchar_t\\*\\*"), stringPtrPtrPat = Pattern.compile("(__)?const char\\*\\*"); protected boolean isString(String typeRefAsString, boolean wide) { if (wide) { return wstringPat.matcher(typeRefAsString).matches() || result.config.charPtrAsString && typeRefAsString.equals("wchar_t*"); } else { return stringPat.matcher(typeRefAsString).matches() || result.config.charPtrAsString && typeRefAsString.equals("char*"); } } protected boolean isStringPtrPtr(String typeRefAsString, boolean wide) { if (wide) { return wstringPtrPtrPat.matcher(typeRefAsString).matches() || result.config.charPtrAsString && typeRefAsString.equals("wchar_t**"); } else { return stringPtrPtrPat.matcher(typeRefAsString).matches() || result.config.charPtrAsString && typeRefAsString.equals("char**"); } } public TypeRef convertTypeToJNA(TypeRef valueType, TypeConversionMode conversionMode, Identifier libraryClassName) throws UnsupportedConversionException { // if (String.valueOf(valueType).contains("MonoImageOpenStatus")) // valueType.toString(); TypeRef original = valueType; valueType = resolveTypeDef(valueType, libraryClassName, true, false); // if (String.valueOf(valueType).contains("MonoObject")) // valueType.toString(); String valueTypeString = String.valueOf(valueType); if (valueTypeString.matches("void\\s*\\*") || valueTypeString.matches("const\\s*void\\s*\\*")) { //valueType = (TypeRef)valueType; if (original instanceof Pointer && result.config.features.contains(GenFeatures.TypedPointersForForwardDeclarations) && allowFakePointers) { Pointer p = (Pointer) original; if (p.getTarget() instanceof SimpleTypeRef) { if (isResolved((SimpleTypeRef) p.getTarget())) { return p.getTarget(); } Identifier name = ((SimpleTypeRef) p.getTarget()).getName(); if (!"void".equals(name.toString()) && name.isPlain()) { // int i = name.lastIndexOf('.'); // if (i >= 0) // name = name.substring(i + 1); return typeRef(result.getFakePointer(libraryClassName, name)); } } } } else { if (conversionMode == TypeConversionMode.ReturnType && result.config.stringifyConstCStringReturnValues) { if (isString(valueTypeString, false)) { return typeRef(String.class); } else if (isString(valueTypeString, true)) { return typeRef(WString.class); } } else if (conversionMode == TypeConversionMode.PrimitiveOrBufferParameter) { if (isString(valueTypeString, false)) { return typeRef(String.class); } else if (isString(valueTypeString, true)) { return typeRef(WString.class); } else if (isStringPtrPtr(valueTypeString, false)) { return arrayRef(typeRef(String.class)); } else if (isStringPtrPtr(valueTypeString, true)) { return arrayRef(typeRef(WString.class)); } /*else if (conversionMode == TypeConversionMode.PrimitiveOrBufferParameter) { if (valueTypeString.matches("char\\*")) return typeRef(StringPointer.ByValue.class); else if (valueTypeString.matches("wchar_t\\*")) return typeRef(WStringPointer.ByValue.class); }*/ } } if (valueType instanceof Primitive) { JavaPrim prim = getPrimitive(valueType, libraryClassName); if (prim != null) { return primRef(prim); } // if (!valueType.getModifiers().contains("long")) // return valueType.toString(); } if (valueType instanceof TaggedTypeRef) { Identifier name = result.declarationsConverter.getActualTaggedTypeName((TaggedTypeRef) valueType); if (name != null) { if (valueType instanceof Enum) { TypeRef tr = findEnum(name, libraryClassName); if (tr != null) { TypeRef intRef = primRef(JavaPrim.Int); intRef.setCommentBefore(tr.getCommentBefore()); return intRef; } } else if (valueType instanceof Struct) { Identifier tr = findStructRef(name, libraryClassName); if (tr != null) { switch (conversionMode) { case PointedValue: case NativeParameterWithStructsPtrPtrs: case NativeParameter: case PrimitiveOrBufferParameter: case ReturnType: case PrimitiveReturnType: case FieldType: return typeRef(tr); case StaticallySizedArrayField: case ExpressionType: default: return typeRef(ident(tr, ident("ByValue"))); } } } } } if (valueType instanceof FunctionSignature) { TypeRef tr = findCallbackRef((FunctionSignature)valueType, libraryClassName); if (tr != null) return tr; else return typeRef(((FunctionSignature)valueType).getFunction().getName().clone()); } if (valueType instanceof TargettedTypeRef) { //TypeRef target = resolveTypeDef(((TargettedTypeRef) valueType).getTarget(), callerLibraryClass); TypeRef target = ((TargettedTypeRef) valueType).getTarget(); boolean staticallySized = valueType instanceof ArrayRef && ((ArrayRef)valueType).hasStaticStorageSize(); TypeRef convArgType = null; JavaPrim prim = getPrimitive(target, libraryClassName); if (prim != null) { if (prim == JavaPrim.Void) return typeRef(result.config.runtime.pointerClass); else convArgType = primRef(prim); } else { Identifier name = null; if (target instanceof SimpleTypeRef) name = ((SimpleTypeRef) target).getName(); else if (target instanceof Struct) { Struct struct = (Struct)target; if (struct == null) { valueType = resolveTypeDef(original, libraryClassName, true, false); struct = null; } else { name = result.declarationsConverter.getActualTaggedTypeName(struct); } } else if (target instanceof FunctionSignature) { TypeRef tr = findCallbackRef((FunctionSignature)target, libraryClassName); if (tr != null) { if (valueType instanceof TypeRef.ArrayRef) { return new TypeRef.ArrayRef(tr); } else { return tr; } } //else // return typeRef(((FunctionSignature)valueType).getFunction().getName()); } else if (target instanceof Pointer) { if (conversionMode == TypeConversionMode.NativeParameter) return typeRef(PointerByReference.class); Pointer pt = ((Pointer)target); TypeRef ptarget = pt.getTarget(); if (ptarget instanceof SimpleTypeRef) { SimpleTypeRef ptargett = (SimpleTypeRef) ptarget; Identifier tname = ptargett.getName(); if (result.structsFullNames.contains(tname)) { if (conversionMode == TypeConversionMode.FieldType) return typeRef(PointerByReference.class); else return new ArrayRef(typeRef(ident(ptargett.getName(), "ByReference"))); } else if ((tname = result.findFakePointer(tname)) != null) return new ArrayRef(typeRef(tname.clone())); } } if (name != null) { /// Pointer to Objective-C class ? convArgType = findObjCClass(name); boolean isQualStruct = result.structsFullNames.contains(name); if (convArgType == null || isQualStruct) { /// Pointer to C structure Identifier structRef = isQualStruct ? name : findStructRef(name, libraryClassName); if (structRef != null) {//result.cStructNames.contains(name)) { switch (conversionMode) { case ExpressionType: case FieldType: convArgType = valueType instanceof TypeRef.ArrayRef ? typeRef(structRef) : typeRef(ident(structRef, ident("ByReference"))); if (valueType instanceof Pointer) return convArgType; break; default: if (isQualStruct && (valueType instanceof ArrayRef) && ( conversionMode == TypeConversionMode.NativeParameterWithStructsPtrPtrs || conversionMode == TypeConversionMode.PrimitiveOrBufferParameter )) return arrayRef(typeRef(structRef)); convArgType = typeRef(structRef); if (valueType instanceof Pointer) return convArgType; break; } } else { try { convArgType = convertTypeToJNA(target, conversionMode, libraryClassName); if (result.isUndefinedType(convArgType)) { if (allowFakePointers && original instanceof SimpleTypeRef) return typeRef(result.getFakePointer(libraryClassName, ((SimpleTypeRef)original).getName().clone())); else convArgType = typeRef(result.config.runtime.pointerClass); } if (convArgType != null && result.callbacksFullNames.contains(ident(convArgType.toString())) && !(valueType instanceof ArrayRef)) { TypeRef tr = typeRef(result.config.runtime.pointerClass); if (!result.config.noComments) tr.setCommentBefore("@see " + convArgType); return tr; } prim = getPrimitive(convArgType, libraryClassName); } catch (UnsupportedConversionException ex) { //convArgType = null;//return typeRef(result.config.runtime.pointerClass); if (valueType instanceof TypeRef.Pointer && target instanceof TypeRef.SimpleTypeRef && result.config.features.contains(JNAeratorConfig.GenFeatures.TypedPointersForForwardDeclarations) && allowFakePointers ) { if (isResolved((SimpleTypeRef) target)) { return target; } // int i = name.lastIndexOf('.'); // if (i >= 0) { // name = name.substring(i + 1); return typeRef(result.getFakePointer(libraryClassName, name)); } else { return typeRef(result.config.runtime.pointerClass); } } } } } else { try { convArgType = convertTypeToJNA(target, conversionMode, libraryClassName); prim = getPrimitive(convArgType, libraryClassName); } catch (UnsupportedConversionException ex) { //convArgType = null;// return typeRef(result.config.runtime.pointerClass); } } } switch (conversionMode) { case StaticallySizedArrayField: return new ArrayRef(convArgType); case PrimitiveOrBufferParameter: if (!result.config.noPrimitiveArrays && (target.getModifiers().contains(ModifierType.Const) || valueType.getModifiers().contains(ModifierType.Const))) { return new ArrayRef(convArgType); } Class<? extends Buffer> bc = primToBuffer.get(prim); if (bc != null) { return typeRef(bc); } case ReturnType: case FieldType: if (staticallySized) { return arrayRef(convArgType); } default: if (prim != null) { if (prim == JavaPrim.Byte) { return typeRef(result.config.runtime.pointerClass).importDetails(convArgType, false); } Class<? extends ByReference> byRefClass = primToByReference.get(prim); if (byRefClass != null) { return typeRef(byRefClass).importDetails(convArgType, false); } } if (convArgType != null && !convArgType.toString().equals(result.config.runtime.pointerClass.getName()) && valueType instanceof TypeRef.Pointer && target instanceof TypeRef.SimpleTypeRef) { return convArgType; } } if (target instanceof Pointer) { return typeRef(PointerByReference.class); } if (allowUnknownPointers) { return typeRef(result.config.runtime.pointerClass); } } if (valueType instanceof SimpleTypeRef) { Identifier name = ((SimpleTypeRef) valueType).getName(); if (name == null) { throw new UnsupportedConversionException(valueType, null); } boolean isQualStruct = result.structsFullNames.contains(name); //isQualCallback = result.callbacksFullNames.contains(name); if (!isQualStruct && isResolved((SimpleTypeRef) valueType)) { return valueType; } if (name instanceof SimpleIdentifier) { TypeRef tr = findObjCClass(name); if (tr == null) { tr = findObjCClass(new SimpleIdentifier(((SimpleIdentifier) name).getName())); } if (tr != null) { return tr; } } Identifier structRef = isQualStruct ? name : findStructRef(name, libraryClassName); if (structRef != null) { switch (conversionMode) { case PointedValue: case FieldType: return typeRef(structRef); default: return typeRef(ident(structRef, "ByValue")); } } TypeRef callbackRef = findCallbackRef(name, libraryClassName); if (callbackRef != null) { return callbackRef; } SimpleTypeRef enumTypeRef = findEnum(name, libraryClassName); //FieldRef enumQualifiedName = findEnum(name); if (enumTypeRef != null) { return enumTypeRef; } TypeRef objCClassRef = findObjCClass(name); if (objCClassRef != null) { return objCClassRef; } } JavaPrim prim = getPrimitive(valueType, libraryClassName); if (prim != null) { return primRef(prim); } if (valueType instanceof SimpleTypeRef && allowFakePointers) { return typeRef(result.getUndefinedType(libraryClassName, ((SimpleTypeRef)valueType).getName().clone())); } unknownTypes.add(String.valueOf(valueType)); throw new UnsupportedConversionException(valueType, null); } static Map<String, Class<?>> predefObjCClasses = new HashMap<String, Class<?>>(); static { predefObjCClasses.put("id", ObjCObject.class);//org.rococoa.ID.class); predefObjCClasses.put("SEL", org.rococoa.Selector.class); predefObjCClasses.put("IMP", com.sun.jna.Pointer.class); predefObjCClasses.put("Class", ObjCClass.class); predefObjCClasses.put("Protocol", ObjCClass.class); predefObjCClasses.put("NSObject", NSObject.class); //predefObjCClasses.put("NSClass", NSClass.class); } public Identifier findObjCClassIdent(Identifier name) { if (name instanceof SimpleIdentifier) { SimpleIdentifier sname = (SimpleIdentifier) name; String n = sname.getName(); if (n.equals("id") && sname.getTemplateArguments().size() == 1/* && conversionMode != TypeConversionMode.NativeParameter && conversionMode != TypeConversionMode.NativeParameterWithStructsPtrPtrs*/) { Expression x = sname.getTemplateArguments().get(0); TypeRefExpression trx = x instanceof TypeRefExpression ? (TypeRefExpression) x : null; SimpleTypeRef str = trx.getType() instanceof SimpleTypeRef ? (SimpleTypeRef) trx.getType() : null; if (str != null) { name = str.getName(); } } } Class<?> class1 = predefObjCClasses.get(name.toString()); if (class1 != null) { return ident(class1); } Struct s = result.getObjcCClassOrProtocol(name); if (s != null) { return result.objectiveCGenerator.getFullClassName(s); } return null; } public TypeRef findObjCClass(Identifier name) { return typeRef(findObjCClassIdent(name)); } private TypeRef arrayRef(TypeRef tr) { ArrayRef arrayRef; if (tr instanceof ArrayRef) { arrayRef = (ArrayRef) tr; arrayRef.addDimension(new Expression.EmptyArraySize()); } else { arrayRef = new ArrayRef(tr); } return arrayRef; } Set<String> unknownTypes = new HashSet<String>(); public static <A, B> Pair<A, B> pair(A a, B b) { return new Pair<A, B>(a, b); } public static Pair<Expression, TypeRef> typed(Expression a, TypeRef b) { return new Pair<Expression, TypeRef>(a, b); } public Pair<Expression, TypeRef> convertExpressionToJava(Expression x, Identifier libraryClassName, boolean promoteNativeLongToLong) throws UnsupportedConversionException { Pair<Expression, TypeRef> res = null; if (x instanceof AssignmentOp) { Pair<Expression, TypeRef> convTarget = convertExpressionToJava(((AssignmentOp) x).getTarget(), libraryClassName, promoteNativeLongToLong), convValue = convertExpressionToJava(((AssignmentOp) x).getValue(), libraryClassName, promoteNativeLongToLong); res = typed(expr(convTarget.getFirst(), AssignmentOperator.Equal, convValue.getFirst()), convTarget.getSecond()); } else if (x instanceof BinaryOp) { BinaryOp bop = (BinaryOp) x; Pair<Expression, TypeRef> conv1 = convertExpressionToJava(bop.getFirstOperand(), libraryClassName, promoteNativeLongToLong), conv2 = convertExpressionToJava(bop.getSecondOperand(), libraryClassName, promoteNativeLongToLong); if (conv1 != null && conv2 != null) { TypeRef t1 = conv1.getSecond(), t2 = conv2.getSecond(); Expression x1 = conv1.getFirst(), x2 = conv2.getFirst(); String s1 = String.valueOf(t1), s2 = String.valueOf(t2); TypeRef tr = null; if (bop.getOperator().givesBool) tr = typeRef(boolean.class); else { if (s1.equals(s2)) { tr = t1; } else { JavaPrim p1 = getPrimitive(t1, null), p2 = getPrimitive(t2, null); if (p1 != null && p2 != null) { switch (bop.getOperator()) { case LeftShift: case RightShift: case SignedRightShift: tr = t1; break; default: for (JavaPrim p : new JavaPrim[]{ JavaPrim.Double, JavaPrim.Float, JavaPrim.Long, JavaPrim.NativeSize, JavaPrim.NativeLong, JavaPrim.Int, JavaPrim.Short, JavaPrim.Byte }) { if (p1 == p || p2 == p) { if (promoteNativeLongToLong && (p == JavaPrim.NativeLong || p == JavaPrim.NativeSize)) { p = JavaPrim.Long; } tr = primRef(p); break; } } } } } } res = typed(expr(x1, ((BinaryOp) x).getOperator(), x2), tr); } } else if (x instanceof UnaryOp) { UnaryOperator op = ((UnaryOp) x).getOperator(); if (op == UnaryOperator.Not) { throw new UnsupportedConversionException(x, null); // TODO handle this properly ? } Pair<Expression, TypeRef> conv = convertExpressionToJava(((UnaryOp) x).getOperand(), libraryClassName, promoteNativeLongToLong); res = typed(expr(op, conv.getFirst()), conv.getSecond()); } else if (x instanceof Cast) { TypeRef tpe = ((Cast) x).getType(); Pair<Expression, TypeRef> casted = convertExpressionToJava(((Cast) x).getTarget(), libraryClassName, promoteNativeLongToLong); if (result.config.runtime.hasJNA) { TypeRef tr = convertTypeToJNA(tpe, TypeConversionMode.ExpressionType, libraryClassName); JavaPrim prim = getPrimitive(tr, libraryClassName); if (promoteNativeLongToLong && (prim == JavaPrim.NativeLong || prim == JavaPrim.NativeSize)) { prim = JavaPrim.Long; tr = typeRef(Long.TYPE); } res = typed(casted.getFirst(), tr); if (prim == JavaPrim.NativeLong) { res.setFirst((Expression) new New(typeRef(com.sun.jna.NativeLong.class), casted.getFirst())); } else if (prim == JavaPrim.NativeSize) { res.setFirst((Expression) new New(typeRef(NativeSize.class), casted.getFirst())); } } else { NL4JConversion conv = convertTypeToNL4J(tpe, libraryClassName, null, null, -1, -1); TypeRef tr = conv.typeRef; res = typed(casted.getFirst(), tr); if (conv.isPtr) { res.setFirst(methodCall(expr(typeRef(result.config.runtime.pointerClass)), "pointerToAddress", casted.getFirst())); } } } else if (x instanceof Constant) { Class<?> c = null; Constant jc = ((Constant) x).asJava(); switch (jc.getType()) { case Byte: c = Byte.TYPE; break; case Char: c = Character.TYPE; break; case Double: c = Double.TYPE; break; case Float: c = Float.TYPE; break; case Int: case UInt: case IntegerString: c = Integer.TYPE; break; case ULong: case Long: case LongString: c = Long.TYPE; break; case Short: c = Short.TYPE; break; case String: c = String.class; break; } if (c != null) { res = typed(((Constant) x).asJava(), typeRef(c)); } } else if (x instanceof VariableRef) { VariableRef fr = (VariableRef) x; Identifier name = fr.getName(); if (name != null) { Define define = result.defines.get(name); if (define != null && define.getValue() != null) { if (x.toString().equals(define.getValue().toString())) { res = null; // avoid some nasty loops } else { Expression defineValue = define.getValue(); if (defineValue instanceof Constant) { Constant constant = (Constant) defineValue; res = typed(findDefine(name), convertToJavaType(constant.getType())); } if (res == null) { res = convertExpressionToJava(defineValue, libraryClassName, promoteNativeLongToLong); } } } else { String sname = name.toString(); if (sname.equals("True") || sname.equals("true")) { res = typed(expr(Constant.Type.Bool, true), primRef(JavaPrim.Boolean)); } else if (sname.equals("False") || sname.equals("false")) { res = typed(expr(Constant.Type.Bool, false), primRef(JavaPrim.Boolean)); } else { EnumItem enumItem = result.enumItems.get(name); if (enumItem != null) { res = typed(findEnumItem(enumItem), typeRef(Integer.TYPE)); } else { VariablesDeclaration constant = result.globalVariablesByName.get(name); if (constant != null) { res = typed(varRef(findRef(name, constant, libraryClassName, true)), null); } else { res = typed(new VariableRef(name), null); } } } } } } else if (x instanceof FunctionCall) { FunctionCall fc = (FunctionCall) x; if ("sizeof".equals(String.valueOf(fc.getFunction())) && fc.getArguments().size() == 1) { TypeRefExpression typeEx = SyntaxUtils.as(fc.getArguments().get(0).getValue(), TypeRefExpression.class); if (typeEx != null) { res = typed(sizeofToJava(typeEx.getType(), libraryClassName), typeRef(Integer.TYPE)); } } } if (x instanceof TypeRefExpression) { TypeRefExpression tre = (TypeRefExpression) x; TypeRef tr = tre.getType(); if (tr instanceof SimpleTypeRef) { SimpleTypeRef str = (SimpleTypeRef) tr; Identifier ident = str.getName(); if (ident != null) { if (result.enumItemsFullName.contains(ident)) { res = typed(tre, typeRef(Integer.TYPE)); } } } if (res == null) { if (tr.isMarkedAsResolved()) { res = typed(tre, tr); } else { TypeRef conv = convertTypeToJNA(tr, TypeConversionMode.ExpressionType, libraryClassName); res = typed(new TypeRefExpression(conv), conv); } } } if (res == null) { // return convertExpressionToJava(x); throw new UnsupportedConversionException(x, null); } if (res.getFirst() == null) { return null; } res.getFirst().setParenthesis(x.getParenthesis()); return (Pair<Expression, TypeRef>) res; } public TypeRef convertToJavaType(Constant.Type type) { switch (type) { case Bool: return typeRef(Boolean.TYPE); case IntegerString: case UInt: case Int: return typeRef(Integer.TYPE); case LongString: case ULong: case Long: return typeRef(Long.TYPE); case Short: return typeRef(Short.TYPE); case Byte: return typeRef(Byte.TYPE); case Float: return typeRef(Float.TYPE); case Double: return typeRef(Double.TYPE); case String: return typeRef(String.class); default: return null; } } private Expression sizeofToJava(TypeRef type, Identifier libraryClassName) throws UnsupportedConversionException { type = resolveTypeDef(type, libraryClassName, true, false); // type = type; Expression res = null; if (type instanceof Pointer) { res = memberRef(expr(typeRef(result.config.runtime.pointerClass)), MemberRefStyle.Dot, "SIZE"); } else if (type instanceof ArrayRef) { res = sizeofToJava(((ArrayRef) type).getTarget(), libraryClassName); if (res == null) { return null; } ArrayRef ar = (ArrayRef) type; for (Expression x : ar.getDimensions()) { Expression c = convertExpressionToJava(x, libraryClassName, false).getFirst(); res = expr(res, Expression.BinaryOperator.Multiply, c); } } else if (type instanceof SimpleTypeRef || type instanceof Primitive) { JavaPrim prim = getPrimitive(type, libraryClassName); if (prim != null) { res = sizeof(prim); } else { Identifier structRef = findStructRef(((SimpleTypeRef) type).getName(), libraryClassName); if (structRef == null) { structRef = findStructRef(((SimpleTypeRef) type).getName().resolveLastSimpleIdentifier(), libraryClassName); } if (structRef != null) { return methodCall(new New(typeRef(structRef)), MemberRefStyle.Dot, "size"); } } } else if (type instanceof Struct) { Struct s = (Struct) type; if (s != null) { Identifier structName = result.declarationsConverter.getActualTaggedTypeName(s); Identifier structRef = findStructRef(structName, libraryClassName); if (structRef != null) { return methodCall(new New(typeRef(structRef)), MemberRefStyle.Dot, "size"); } else { for (Declaration d : s.getDeclarations()) { if (d instanceof VariablesDeclaration) { TypeRef varsType = d.getValueType(); for (Declarator sto : ((VariablesDeclaration) d).getDeclarators()) { Expression so = sizeofToJava(as(sto.mutateType(varsType), TypeRef.class), libraryClassName); if (so == null) { return null; } if (res == null) { res = so; } else { res = expr(res, Expression.BinaryOperator.Plus, so); } } } } } } } return res; } private Expression sizeof(JavaPrim prim) { return prim.size.sizeof(prim); } private Expression findEnumItem(EnumItem enumItem) { String library = result.getLibrary(enumItem); if (library == null) { return null; } Element parent = enumItem.getParentElement(); if (parent == null || !(parent instanceof Enum)) { return null; } Enum e = (Enum) parent; Identifier ident = ident(result.getLibraryClassFullName(library), result.declarationsConverter.getActualTaggedTypeName(e), ident(enumItem.getName())); return expr(typeRef(ident).setMarkedAsResolved(true)); } public static Set<String> JAVA_KEYWORDS = new HashSet<String>(Arrays.asList( "null", "true", "false", "abstract", "continue", "for", "new", "switch", "assert", "default", "goto", "package", "synchronized", "boolean", "do", "if", "private", "this", "break", "double", "implements", "protected", "throw", "byte", "else", "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", "native", "super", "while", "wait" // not allowed for function names )); //static String keywords = " true false double float wait new null boolean return class public protected private "; public Identifier getValidJavaArgumentName(Identifier name) { return getValidJavaIdentifier(name); } public Identifier getValidJavaMethodName(Identifier name) { String nameStr = name.toString(); String newName = null; if (nameStr.matches("operator[^\\w]+")) { String op = nameStr.substring("operator".length()); //int nArgs = method.getArgs().size(); String suffix = null; java.lang.Enum<?> e = Expression.getAnyOperator(op); if (e == null) { if (op.equals("()")) { suffix = "parenthesis"; } else if (op.equals("[]")) { suffix = "brackets"; } else if (op.equals("->")) { suffix = "arrow"; } } else { suffix = e.name(); } if (suffix != null) { newName = "operator" + StringUtils.capitalize(suffix); } }/* else if (nameStr.startsWith("~")) { newName = getValidJavaIdentifierString(ident(nameStr.substring(1))) + "Destructor"; }*/ if (newName == null) { newName = getValidJavaIdentifierString(name); } else if (result.config.beautifyNames) { newName = beautify(newName); } return ident(newName); } String beautify(String name) { String newName = StringUtils.uncapitalize(StringUtils.underscoredToCamel(name)); if (name.endsWith("_")) { newName += "$"; } return newName; } public boolean isJavaKeyword(String name) { return JAVA_KEYWORDS.contains(name); } public Identifier getValidJavaIdentifier(Identifier name) { return ident(getValidJavaIdentifierString(name)); } public String getValidJavaIdentifierString(Identifier name) { if (name == null) { return null; } if (isJavaKeyword(name.toString())) { return name + "$"; } else { String newName = name.toString().replace('-', '_').replaceAll("[^\\w]", "\\$"); if (result.config.beautifyNames) { newName = beautify(newName); } return newName; } } public static String toPrimString(JavaPrim prim) { return prim.name; } public Expression getJavaClassLitteralExpression(TypeRef tr) { JavaPrim prim = result.typeConverter.getPrimitive(tr, null); return prim != null ? classLiteral(prim.type) : typeLiteral(tr.clone()); } public Expression getJavaClassLitteralExpression() { throw new UnsupportedOperationException(getClass().getName() + "." + toString() + " not handled !"); } }
package com.matthewtamlin.android_utilities.library.testing; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.LinearLayout; /** * An activity which hosts a view to be tested, as well as controls for interacting with the view. * * @param <V> * the type of view being tested * @param <C> * the type of view which contains the test view */ public abstract class TestHarness<V, C> extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } /** * @return the root view of this Activity's layout, not null */ public abstract View getRootView(); /** * @return the view which contains the controls, not null */ public abstract LinearLayout getControlsContainer(); /** * @return the view under test, not null */ public abstract V getTestView(); /** * @return the view which contains the test view */ public abstract C getTestViewContainer(); }
package ca.teamTen.recitopia; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.util.ArrayList; /** * RecipeBook class which can be used to store, query recipes * without interacting with (many) external systems. * * Good for storing recipes locally on the filesystem, for * instance. * * Child classes can implement hook methods to ensure the * recipe book can satisfy their constraints. * * @see RecipeBook */ public class SimpleRecipeBook implements RecipeBook { /** * Factory that creates input/output streams used for * loading/saving (respectively). * * If either method returns null, the load/save is not * executed. */ public interface IOFactory { InputStream getInputStream() throws IOException; OutputStream getOutputStream() throws IOException; } /** * Simple IOFactory implementation that always returns * null. */ public static class NullIOFactory implements IOFactory { @Override public InputStream getInputStream() throws IOException { return null; } @Override public OutputStream getOutputStream() throws IOException { return null; } } protected ArrayList<Recipe> recipes = new ArrayList<Recipe>(); private IOFactory ioFactory; public SimpleRecipeBook(IOFactory io) { ioFactory = io; } public SimpleRecipeBook() { ioFactory = new NullIOFactory(); } /** * Implement Google-style searching of recipes, with no indexing. */ @Override public Recipe[] query(String searchTerms) { String[] queryTerms = searchTerms.split("\\s+"); // split query into tokens by whitespace ArrayList<Recipe> results = new ArrayList<Recipe>(); for (Recipe recipe: recipes) { if (recipeMatchesQuery(recipe, queryTerms)) { results.add(recipe); } } Recipe[] resultArray = new Recipe[results.size()]; return results.toArray(resultArray); } /** * Adds a recipe to this recipe book. If a recipe already exists with the * same title and author, it will be updated. * * @see ca.teamTen.recitopia.RecipeBook#addRecipe(ca.teamTen.recitopia.Recipe) */ @Override public void addRecipe(Recipe recipe) { for (int i = 0; i < recipes.size(); i++) { Recipe current = recipes.get(i); if (current.getRecipeName().equals(recipe.getRecipeName()) && current.getAuthor().equals(recipe.getAuthor())) { recipes.set(i, recipe); this.recipeUpdated(recipe, i); return; } } recipes.add(recipe); this.recipeAdded(recipe); } /** * Hook method called when a new Recipe is added. * @param recipe which was added at index recipes.size() - 1 */ protected void recipeAdded(Recipe recipe) { } /** * Hook method called when a Recipe is updated. * * @param recipe the new value of the recipe * @param i the index of the recipe */ protected void recipeUpdated(Recipe recipe, int i) { } /** * Checks whether recipe matches any terms from query. All text fields * (author, title, instructions, ingredients) of the recipe are searched. * * Uses case-insensitive searching. * * @param recipe * @param query An array of search terms. These need no special formatting. * @return */ protected boolean recipeMatchesQuery(Recipe recipe, String[] query) { // for an empty query, everything matches if (query.length == 1 && query.equals("")) { return true; } for (String term: query) { if (query.equals("")) { continue; // if we have multiple terms, we should ignore empty ones. } term = term.toLowerCase(); if (recipe.getAuthor().toLowerCase().contains(term) || recipe.getRecipeName().toLowerCase().contains(term) || recipe.getCookingInstructions().toLowerCase().contains(term)) { return true; } for (String ingredient: recipe.getIngredients()) { if (ingredient.toLowerCase().contains(term)) { return true; } } } return false; } /** * Saves recipes to the loutput stream returned by the IOFactory. */ public void save() { try { OutputStream rawOutputStream = ioFactory.getOutputStream(); if (rawOutputStream == null) { return; } ObjectOutputStream out = new ObjectOutputStream(rawOutputStream); out.writeObject(recipes); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * Loads recipes from an InputStream returned by the * IOFactory. */ public void load() { try { InputStream rawStream = ioFactory.getInputStream(); if (rawStream == null) { return; } ObjectInputStream in = new ObjectInputStream(rawStream); recipes = (ArrayList<Recipe>) in.readObject(); in.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
package ch.ntb.inf.deep.launcher; import ch.ntb.inf.deep.config.Configuration; import ch.ntb.inf.deep.host.ErrorReporter; import ch.ntb.inf.deep.linker.Linker32; /** * Launcher for tests only! Adapt this file to your configuration, but don't commit * those changes to the SVN! Please store your project file in the top folder of * the deep-Project. You can find an example project "ExampleProject.deep" in * this folder which you may use as base for your own test project. */ public class TestLauncher { public static void main(String[] args) { Launcher.buildAll("M:/EUser/JCC/deep/555ExampleProject.deep", "BootFromRam"); // Launcher.buildAll("M:/EUser/JCC/deep/555junitTarget.deep", "BootFromRam"); // Launcher.buildAll("M:/EUser/JCC/deep/5200ExampleProject.deep", "BootFromRam"); if (ErrorReporter.reporter.nofErrors == 0) { Launcher.openTargetConnection(); Launcher.downloadTargetImage(); Launcher.startTarget(); Launcher.closeTargetConnection(); } // Launcher.saveTargetImageToFile("W:/phycorempc5200b/test.bin", Configuration.BIN); System.out.println("image file created"); // Launcher.createInterfaceFile("M:/EUser\\JCC\\bsp\\src\\ch\\ntb\\inf\\deep\\runtime\\mpc5200\\phyCoreMpc5200tiny.java"); /* DEBUG OUTPRINTS */ // System.out.println("%%%%%%%%%%%%%%% Class List %%%%%%%%%%%%%%%"); Linker32.printClassList(true, false, false, true); // System.out.println("%%%%%%%%%%%%%%% System Table %%%%%%%%%%%%%%%"); Linker32.printSystemTable(); // System.out.println("%%%%%%%%%%%%%%% Global Constants %%%%%%%%%%%%%%%"); Linker32.printGlobalConstantTable(); // System.out.println("%%%%%%%%%%%%%%% Target Image (Full image) %%%%%%%%%%%%%%%"); Linker32.printTargetImage(); // System.out.println("%%%%%%%%%%%%%%% Target Image (Segment List) %%%%%%%%%%%%%%%"); Linker32.printTargetImageSegmentList(); // System.out.println("%%%%%%%%%%%%%%% Memory Map %%%%%%%%%%%%%%%"); MemoryMap.getInstance().println(1); // System.out.println("%%%%%%%%%%%%%%% Configuration %%%%%%%%%%%%%%%"); Configuration.print(); // System.out.println("%%%%%%%%%%%%%%% Compiler specific subroutines %%%%%%%%%%%%%%%"); Method.printCompSpecificSubroutines(); } }
package com.ecyrd.jspwiki.tags; import com.ecyrd.jspwiki.WikiEngine; import com.ecyrd.jspwiki.WikiContext; import org.apache.log4j.Category; import javax.servlet.http.HttpSession; import javax.servlet.jsp.JspWriter; import java.io.IOException; import java.io.Serializable; import java.util.LinkedList; /** * Implement a "breadcrumb" (most recently visited) trail. This tag can be added to any view jsp page. * Separate breadcrumb trails are not tracked across multiple browser windows.<br> * The optional attributes are: * <p> * <b>maxpages</b>, the number of pages to store, 10 by default<br> * <b>separator</b>, the separator string to use between pages, " | " by default<br> * </p> * * <p> * This class is implemented by storing a breadcrumb trail, which is a * fixed size queue, into a session variable "breadCrumbTrail". * This queue is displayed as a series of links separated by a separator * character. * </p> * @author Ken Liu ken@kenliu.net */ public class BreadcrumbsTag extends WikiTagBase { private static final Category log = Category.getInstance(BreadcrumbsTag.class); private static final String BREADCRUMBTRAIL_KEY = "breadCrumbTrail"; private int m_maxQueueSize = 11; private String m_separator = " | "; public int getMaxpages() { return m_maxQueueSize; } public void setMaxpages(int maxpages) { m_maxQueueSize = maxpages + 1; } public String getSeparator() { return m_separator; } public void setSeparator(String separator) { m_separator = separator; } public final int doWikiStartTag() throws IOException { HttpSession session = pageContext.getSession(); FixedQueue trail = (FixedQueue) session.getAttribute(BREADCRUMBTRAIL_KEY); String page = m_wikiContext.getPage().getName(); if( trail == null ) { trail = new FixedQueue(m_maxQueueSize); } if( m_wikiContext.getRequestContext().equals( WikiContext.VIEW ) ) { if( trail.isEmpty() ) { trail.push(page); } else { // Don't add the page to the queue if the page was just refreshed if( !((String) trail.getLast()).equals(page) ) { trail.push(page); log.debug("added page: " + page); } log.debug("didn't add page because of refresh"); } } session.setAttribute(BREADCRUMBTRAIL_KEY, trail); // Print out the breadcrumb trail // FIXME: this code would be much simpler if we could just output the [pagename] and then use the // wiki engine to output the appropriate wikilink JspWriter out = pageContext.getOut(); int queueSize = trail.size(); String linkclass = "wikipage"; WikiEngine engine = m_wikiContext.getEngine(); String curPage = null; for( int i = 0; i < queueSize - 1; i++ ) { curPage = (String) trail.get(i); //FIXME: I can't figure out how to detect the appropriate jsp page to put here, so I hard coded Wiki.jsp //This breaks when you view an attachment metadata page out.print("<A CLASS=\"" + linkclass + "\" HREF=\"" + engine.getViewURL(curPage)+ "\">" + curPage + "</A>"); if( i < queueSize - 2 ) { out.print(m_separator); } } return SKIP_BODY; } /** * Extends the LinkedList class to provide a fixed-size queue implementation */ private class FixedQueue extends LinkedList implements Serializable { private int m_size; FixedQueue(int size) { m_size = size; } Object push(Object o) { add(o); if( size() > m_size ) return removeFirst(); else return null; } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dae.prefabs.standard; import com.jme3.asset.AssetManager; import com.jme3.scene.Spatial; import dae.prefabs.Prefab; /** * This class describes a camera. The main property of a camera is its id. * * @author Koen */ public class CameraEntity extends Prefab { private String cameraId; private boolean startCam; public CameraEntity() { } @Override public void create(AssetManager manager, String extraInfo) { Spatial node = manager.loadModel("Entities/Entity_Camera.j3o"); this.attachChild(node); this.setCategory("Standard"); this.setType("Camera"); } public void setCameraId(String eventid) { this.cameraId = eventid; } public String getCameraId() { return cameraId; } public boolean getStartCam() { return startCam; } public void setStartCam(boolean startCam) { this.startCam = startCam; } }
package com.googlecode.jmxtrans.util; import java.io.File; import java.io.IOException; import java.lang.reflect.Array; import java.rmi.UnmarshalException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.MBeanAttributeInfo; import javax.management.MBeanInfo; import javax.management.MBeanServerConnection; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeDataSupport; import javax.management.openmbean.CompositeType; import javax.management.openmbean.TabularDataSupport; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import javax.naming.Context; import org.apache.commons.lang.StringUtils; import org.apache.commons.pool.KeyedObjectPool; import org.apache.commons.pool.impl.GenericKeyedObjectPool; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectWriter; import org.codehaus.jackson.map.SerializationConfig.Feature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.googlecode.jmxtrans.OutputWriter; import com.googlecode.jmxtrans.model.JmxProcess; import com.googlecode.jmxtrans.model.Query; import com.googlecode.jmxtrans.model.Result; import com.googlecode.jmxtrans.model.Server; /** * The worker code. * * @author jon */ public class JmxUtils { private static final Logger log = LoggerFactory.getLogger(JmxUtils.class); /** * Merges two lists of servers (and their queries). Based on the equality of both sets of objects. * Public for testing purposes. */ public static void mergeServerLists(List<Server> existing, List<Server> adding) { for (Server server : adding) { if (existing.contains(server)) { Server found = existing.get(existing.indexOf(server)); List<Query> queries = server.getQueries(); for (Query q : queries) { try { // no need to check for existing since this method already does that found.addQuery(q); } catch (ValidationException ex) { // catching this exception because we don't want to stop processing log.error("Error adding query: " + q + " to server" + server, ex); } } } else { existing.add(server); } } } /** * Either invokes the queries multithreaded (max threads == server.getMultiThreaded()) * or invokes them one at a time. */ public static void processQueriesForServer(final MBeanServerConnection mbeanServer, Server server) throws Exception { if (server.isQueriesMultiThreaded()) { ExecutorService service = null; try { service = Executors.newFixedThreadPool(server.getNumQueryThreads()); if (log.isDebugEnabled()) { log.debug(" } List<Callable<Object>> threads = new ArrayList<Callable<Object>>(server.getQueries().size()); for (Query query : server.getQueries()) { query.setServer(server); ProcessQueryThread pqt = new ProcessQueryThread(mbeanServer, query); threads.add(Executors.callable(pqt)); } service.invokeAll(threads); } finally { shutdownAndAwaitTermination(service); } } else { for (Query query : server.getQueries()) { query.setServer(server); processQuery(mbeanServer, query); } } } /** * Copied from the Executors javadoc. */ private static void shutdownAndAwaitTermination(ExecutorService service) { service.shutdown(); // Disable new tasks from being submitted try { // Wait a while for existing tasks to terminate if (!service.awaitTermination(60, TimeUnit.SECONDS)) { service.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if (!service.awaitTermination(60, TimeUnit.SECONDS)) { log.error("Pool did not terminate"); } } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted service.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } } /** * Executes either a getAttribute or getAttributes query. */ public static class ProcessQueryThread implements Runnable { private MBeanServerConnection mbeanServer; private Query query; public ProcessQueryThread(MBeanServerConnection mbeanServer, Query query) { this.mbeanServer = mbeanServer; this.query = query; } public void run() { try { processQuery(this.mbeanServer, this.query); } catch (Exception e) { log.error("Error executing query", e); throw new RuntimeException(e); } } } /** * Responsible for processing individual Queries. */ public static void processQuery(MBeanServerConnection mbeanServer, Query query) throws Exception { ObjectName oName = new ObjectName(query.getObj()); Set<ObjectName> queryNames = mbeanServer.queryNames(oName, null); for (ObjectName queryName : queryNames) { List<Result> resList = new ArrayList<Result>(); MBeanInfo info = mbeanServer.getMBeanInfo(queryName); ObjectInstance oi = mbeanServer.getObjectInstance(queryName); List<String> queryAttributes = query.getAttr(); if ((queryAttributes == null) || (queryAttributes.size() == 0)) { MBeanAttributeInfo[] attrs = info.getAttributes(); for (MBeanAttributeInfo attrInfo : attrs) { query.addAttr(attrInfo.getName()); } } try { if ((query.getAttr() != null) && (query.getAttr().size() > 0)) { if (log.isDebugEnabled()) { log.debug("Executing queryName: " + queryName.getCanonicalName() + " from query: " + query); } AttributeList al = mbeanServer.getAttributes(queryName, query.getAttr().toArray(new String[query.getAttr().size()])); for (Attribute attribute : al.asList()) { getResult(resList, info, oi, attribute, query); } query.setResults(resList); // Now run the OutputWriters. runOutputWritersForQuery(query); if (log.isDebugEnabled()) { log.debug("Finished running outputWriters for query: " + query); } } } catch (UnmarshalException ue) { if ((ue.getCause() != null) && (ue.getCause() instanceof ClassNotFoundException)) { log.debug("Bad unmarshall, continuing. This is probably ok and due to something like this: " + "http://ehcache.org/xref/net/sf/ehcache/distribution/RMICacheManagerPeerListener.html#52", ue.getMessage()); } } } } /** * Populates the Result objects. This is a recursive function. Query contains the * keys that we want to get the values of. */ private static void getResult(List<Result> resList, MBeanInfo info, ObjectInstance oi, String attributeName, CompositeData cds, Query query) { CompositeType t = cds.getCompositeType(); Result r = getNewResultObject(info, oi, attributeName, query); Set<String> keys = t.keySet(); for (String key : keys) { Object value = cds.get(key); if (value instanceof TabularDataSupport) { TabularDataSupport tds = (TabularDataSupport) value; processTabularDataSupport(resList, info, oi, r, attributeName + "." + key, tds, query); r.addValue(key, value.toString()); } else if (value instanceof CompositeDataSupport) { // now recursively go through everything. CompositeDataSupport cds2 = (CompositeDataSupport) value; getResult(resList, info, oi, attributeName, cds2, query); return; // because we don't want to add to the list yet. } else { r.addValue(key, value.toString()); } } resList.add(r); } private static void processTabularDataSupport(List<Result> resList, MBeanInfo info, ObjectInstance oi, Result r, String attributeName, TabularDataSupport tds, Query query) { Set<Entry<Object,Object>> entries = tds.entrySet(); for (Entry<Object, Object> entry : entries) { Object entryKeys = entry.getKey(); if (entryKeys instanceof List) { // ie: attributeName=LastGcInfo.Par Survivor Space // i haven't seen this be smaller or larger than List<1>, but might as well loop it. StringBuilder sb = new StringBuilder(); for (Object entryKey : (List<?>)entryKeys) { sb.append("."); sb.append(entryKey); } String attributeName2 = sb.toString(); Object entryValue = entry.getValue(); if (entryValue instanceof CompositeDataSupport) { getResult(resList, info, oi, attributeName + attributeName2, (CompositeDataSupport)entryValue, query); } else { throw new RuntimeException("!!!!!!!!!! Please file a bug: http://code.google.com/p/jmxtrans/issues/entry entryValue is: " + entryValue.getClass().getCanonicalName()); } } else { throw new RuntimeException("!!!!!!!!!! Please file a bug: http://code.google.com/p/jmxtrans/issues/entry entryKeys is: " + entryKeys.getClass().getCanonicalName()); } } } /** * Builds up the base Result object */ private static Result getNewResultObject(MBeanInfo info, ObjectInstance oi, String attributeName, Query query) { Result r = new Result(attributeName); r.setQuery(query); r.setClassName(info.getClassName()); r.setTypeName(oi.getObjectName().getCanonicalKeyPropertyListString()); return r; } /** * Used when the object is effectively a java type */ private static void getResult(List<Result> resList, MBeanInfo info, ObjectInstance oi, Attribute attribute, Query query) { Object value = attribute.getValue(); if (value != null) { if (value instanceof CompositeDataSupport) { getResult(resList, info, oi, attribute.getName(), (CompositeData) value, query); } else if (value instanceof CompositeData[]) { for (CompositeData cd : (CompositeData[])value) { getResult(resList, info, oi, attribute.getName(), cd, query); } } else if (value instanceof ObjectName[]) { Result r = getNewResultObject(info, oi, attribute.getName(), query); for (ObjectName obj : (ObjectName[])value) { r.addValue(obj.getCanonicalName(), obj.getKeyPropertyListString()); } resList.add(r); } else if (value.getClass().isArray()) { // OMFG: this is nutty. some of the items in the array can be primitive! great interview question! Result r = getNewResultObject(info, oi, attribute.getName(), query); for (int i = 0; i < Array.getLength(value); i++) { Object val = Array.get(value, i); r.addValue(attribute.getName() + "." + i, val); } resList.add(r); } else if (value instanceof TabularDataSupport) { TabularDataSupport tds = (TabularDataSupport) value; Result r = getNewResultObject(info, oi, attribute.getName(), query); processTabularDataSupport(resList, info, oi, r, attribute.getName(), tds, query); resList.add(r); } else { Result r = getNewResultObject(info, oi, attribute.getName(), query); r.addValue(attribute.getName(), value.toString()); resList.add(r); } } } private static void runOutputWritersForQuery(Query query) throws Exception { List<OutputWriter> writers = query.getOutputWriters(); if (writers != null) { for (OutputWriter writer : writers) { writer.doWrite(query); } } } /** * Helper method for connecting to a Server. You need to close the resulting connection. */ public static JMXConnector getServerConnection(Server server) throws Exception { JMXServiceURL url = new JMXServiceURL(server.getUrl()); if (server.getProtocolProviderPackages() != null && server.getProtocolProviderPackages().contains("weblogic")) return JMXConnectorFactory.connect(url, getWebLogicEnvironment(server)); else return JMXConnectorFactory.connect(url, getEnvironment(server)); } /** * Generates the proper username/password environment for JMX connections. */ public static Map<String, String> getWebLogicEnvironment(Server server) { Map<String, String> environment = new HashMap<String, String>(); String username = server.getUsername(); String password = server.getPassword(); if ((username != null) && (password != null)) { environment.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, server.getProtocolProviderPackages()); environment.put(Context.SECURITY_PRINCIPAL, username); environment.put(Context.SECURITY_CREDENTIALS, password); } return environment; } /** * Generates the proper username/password environment for JMX connections. */ public static Map<String, String[]> getEnvironment(Server server) { Map<String, String[]> environment = new HashMap<String, String[]>(); String username = server.getUsername(); String password = server.getPassword(); if ((username != null) && (password != null)) { String[] credentials = new String[2]; credentials[0] = username; credentials[1] = password; environment.put(JMXConnector.CREDENTIALS, credentials); } return environment; } /** * Either invokes the servers multithreaded (max threads == jmxProcess.getMultiThreaded()) * or invokes them one at a time. */ public static void execute(JmxProcess process) throws Exception { List<JMXConnector> conns = new ArrayList<JMXConnector>(); if (process.isServersMultiThreaded()) { ExecutorService service = null; try { service = Executors.newFixedThreadPool(process.getNumMultiThreadedServers()); for (Server server : process.getServers()) { JMXConnector conn = JmxUtils.getServerConnection(server); conns.add(conn); service.execute(new ProcessServerThread(server, conn)); } service.shutdown(); } finally { try { service.awaitTermination(1000 * 60, TimeUnit.SECONDS); } catch (InterruptedException ex) { log.error("Error shutting down execution.", ex); } } } else { for (Server server : process.getServers()) { JMXConnector conn = JmxUtils.getServerConnection(server); conns.add(conn); processServer(server, conn); } } for (JMXConnector conn : conns) { try { conn.close(); } catch (Exception ex) { log.error("Error closing connection.", ex); } } } /** * Executes either a getAttribute or getAttributes query. */ public static class ProcessServerThread implements Runnable { private Server server; private JMXConnector conn; public ProcessServerThread(Server server, JMXConnector conn) { this.server = server; this.conn = conn; } public void run() { try { processServer(this.server, this.conn); } catch (Exception e) { throw new RuntimeException(e); } } } /** * Does the work for processing a Server object. */ public static void processServer(Server server, JMXConnector conn) throws Exception { // try { MBeanServerConnection mbeanServer = conn.getMBeanServerConnection(); JmxUtils.processQueriesForServer(mbeanServer, server); // } catch (IOException e) { // log.error("Problem processing queries for server: " + server.getHost() + ":" + server.getPort(), e); // } finally { // if (conn != null) { // conn.close(); } /** * Utility function good for testing things. Prints out the json * tree of the JmxProcess. */ public static void printJson(JmxProcess process) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().set(Feature.WRITE_NULL_MAP_VALUES, false); System.out.println(mapper.writeValueAsString(process)); } /** * Utility function good for testing things. Prints out the json * tree of the JmxProcess. */ public static void prettyPrintJson(JmxProcess process) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().set(Feature.WRITE_NULL_MAP_VALUES, false); ObjectWriter writer = mapper.defaultPrettyPrintingWriter(); System.out.println(writer.writeValueAsString(process)); } /** * Uses jackson to load json configuration from a File into a full object * tree representation of that json. */ public static JmxProcess getJmxProcess(File file) throws JsonParseException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); JmxProcess jmx = mapper.readValue(file, JmxProcess.class); jmx.setName(file.getName()); return jmx; } /** * Useful for figuring out if an Object is a number. */ public static boolean isNumeric(Object value) { return (((value instanceof String) && isNumeric((String)value)) || (value instanceof Number) || (value instanceof Integer) || (value instanceof Long) || (value instanceof Double) || (value instanceof Float)); } /** * <p>Checks if the String contains only unicode digits. * A decimal point is a digit and returns true.</p> * * <p><code>null</code> will return <code>false</code>. * An empty String ("") will return <code>true</code>.</p> * * <pre> * StringUtils.isNumeric(null) = false * StringUtils.isNumeric("") = true * StringUtils.isNumeric(" ") = false * StringUtils.isNumeric("123") = true * StringUtils.isNumeric("12 3") = false * StringUtils.isNumeric("ab2c") = false * StringUtils.isNumeric("12-3") = false * StringUtils.isNumeric("12.3") = true * </pre> * * @param str the String to check, may be null * @return <code>true</code> if only contains digits, and is non-null */ public static boolean isNumeric(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { char cat = str.charAt(i); if (cat == '.') { continue; } else if (Character.isDigit(cat) == false) { return false; } } return true; } /** * Helper method which returns a default PoolMap. * * TODO: allow for more configuration options? */ public static Map<String, KeyedObjectPool> getDefaultPoolMap() { Map<String, KeyedObjectPool> poolMap = new HashMap<String, KeyedObjectPool>(); GenericKeyedObjectPool pool = new GenericKeyedObjectPool(new SocketFactory()); pool.setTestOnBorrow(true); pool.setMaxActive(-1); pool.setMaxIdle(-1); pool.setTimeBetweenEvictionRunsMillis(1000 * 60 * 5); pool.setMinEvictableIdleTimeMillis(1000 * 60 * 5); poolMap.put(Server.SOCKET_FACTORY_POOL, pool); GenericKeyedObjectPool jmxPool = new GenericKeyedObjectPool(new JmxConnectionFactory()); jmxPool.setTestOnBorrow(true); jmxPool.setMaxActive(-1); jmxPool.setMaxIdle(-1); jmxPool.setTimeBetweenEvictionRunsMillis(1000 * 60 * 5); jmxPool.setMinEvictableIdleTimeMillis(1000 * 60 * 5); poolMap.put(Server.JMX_CONNECTION_FACTORY_POOL, jmxPool); GenericKeyedObjectPool dsPool = new GenericKeyedObjectPool(new DatagramSocketFactory()); dsPool.setTestOnBorrow(true); dsPool.setMaxActive(-1); dsPool.setMaxIdle(-1); dsPool.setTimeBetweenEvictionRunsMillis(1000 * 60 * 5); dsPool.setMinEvictableIdleTimeMillis(1000 * 60 * 5); poolMap.put(Server.DATAGRAM_SOCKET_FACTORY_POOL, dsPool); return poolMap; } public static String getKeyString(Query query, Result result, Entry<String, Object> values, List<String> typeNames, String rootPrefix) { String keyStr = null; if (values.getKey().startsWith(result.getAttributeName())) { keyStr = values.getKey(); } else { keyStr = result.getAttributeName() + "." + values.getKey(); } String alias = null; if (query.getServer().getAlias() != null) { alias = query.getServer().getAlias(); } else { alias = query.getServer().getHost() + "_" + query.getServer().getPort(); alias = cleanupStr(alias); } StringBuilder sb = new StringBuilder(); if (rootPrefix != null) { sb.append(rootPrefix); sb.append("."); } sb.append(alias); sb.append("."); // Allow people to use something other than the classname as the output. if (result.getClassNameAlias() != null) { sb.append(result.getClassNameAlias()); } else { sb.append(cleanupStr(result.getClassName())); } sb.append("."); String typeName = cleanupStr(getConcatedTypeNameValues(query, typeNames, result.getTypeName())); if (typeName != null) { sb.append(typeName); sb.append("."); } sb.append(cleanupStr(keyStr)); return sb.toString(); } public static String getKeyString2(Query query, Result result, Entry<String, Object> values, List<String> typeNames, String rootPrefix) { String keyStr = null; if (values.getKey().startsWith(result.getAttributeName())) { keyStr = values.getKey(); } else { keyStr = result.getAttributeName() + "." + values.getKey(); } StringBuilder sb = new StringBuilder(); // Allow people to use something other than the classname as the output. if (result.getClassNameAlias() != null) { sb.append(result.getClassNameAlias()); } else { sb.append(cleanupStr(result.getClassName())); } sb.append("."); String typeName = cleanupStr(getConcatedTypeNameValues(query, typeNames, result.getTypeName())); if (typeName != null) { sb.append(typeName); sb.append("."); } sb.append(cleanupStr(keyStr)); return sb.toString(); } /** * Replaces all . with _ and removes all spaces and double/single quotes. */ public static String cleanupStr(String name) { if (name == null) { return null; } String clean = name.replace(".", "_"); clean = clean.replace(" ", ""); clean = clean.replace("\"", ""); clean = clean.replace("'", ""); return clean; } /** * Given a typeName string, get the first match from the typeNames setting. * In other words, suppose you have: * * typeName=name=PS Eden Space,type=MemoryPool * * If you addTypeName("name"), then it'll retrieve 'PS Eden Space' from the string */ public static String getConcatedTypeNameValues(List<String> typeNames, String typeNameStr) { if ((typeNames == null) || (typeNames.size() == 0)) { return null; } String[] tokens = typeNameStr.split(","); StringBuilder sb = new StringBuilder(); for (String key : typeNames) { String result = getTypeNameValue(key, tokens); if (result != null) { sb.append(result); sb.append("_"); } } return StringUtils.chomp(sb.toString(), "_"); } /** * Given a typeName string, get the first match from the typeNames setting. * In other words, suppose you have: * * typeName=name=PS Eden Space,type=MemoryPool * * If you addTypeName("name"), then it'll retrieve 'PS Eden Space' from the * string */ public static String getConcatedTypeNameValues(Query query, List<String> typeNames, String typeName) { Set<String> queryTypeNames = query.getTypeNames(); if (queryTypeNames != null && queryTypeNames.size() > 0) { List<String> allNames = new ArrayList<String>(queryTypeNames); for (String name : typeNames) { if (!allNames.contains(name)) { allNames.add(name); } } return getConcatedTypeNameValues(allNames, typeName); } else { return getConcatedTypeNameValues(typeNames, typeName); } } private static String getTypeNameValue(String typeName, String[] tokens) { boolean foundIt = false; for (String token : tokens) { String[] keys = token.split("="); for (String key : keys) { // we want the next item in the array. if (foundIt) { return key; } if (typeName.equals(key)) { foundIt = true; } } } return null; } }
package com.googlecode.networklog; import android.util.Log; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.Filter; import android.widget.Filterable; import android.view.View; import android.view.ViewGroup; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.graphics.drawable.Drawable; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Toast; import android.util.TypedValue; import android.view.MenuItem; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuInflater; import android.widget.AdapterView.AdapterContextMenuInfo; /* newer API 11 clipboard unsupported on older APIs import android.content.ClipboardManager; import android.content.ClipData; */ /* use older clipboard API to support older devices */ import android.text.ClipboardManager; import android.support.v4.app.Fragment; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; public class LogFragment extends Fragment { // bound to adapter protected LinkedList<ListItem> listData; // buffers incoming log entries protected LinkedList<ListItem> listDataBuffer; // holds all entries, used for filtering protected LinkedList<ListItem> listDataUnfiltered; private CustomAdapter adapter; private ListViewUpdater updater; private NetworkLog parent = null; public long maxLogEntries; private boolean doNotRefresh = false; public boolean needsRefresh = false; protected class ListItem { protected ApplicationsTracker.AppEntry app; protected String in; protected String out; protected String proto; protected String srcAddr; protected int srcPort; protected String dstAddr; protected int dstPort; protected int len; protected long timestamp; ListItem(ApplicationsTracker.AppEntry app) { this.app = app; } @Override public String toString() { return app.name; } } public void clear() { synchronized(listData) { synchronized(listDataBuffer) { synchronized(listDataUnfiltered) { listData.clear(); listDataBuffer.clear(); listDataUnfiltered.clear(); refreshAdapter(); } } } } public void setDoNotRefresh(boolean value) { doNotRefresh = value; } public void refreshAdapter() { if(doNotRefresh) { return; } adapter.notifyDataSetChanged(); if(MyLog.enabled) { MyLog.d("Refreshed LogFragment adapter"); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); setUserVisibleHint(true); } public void setParent(NetworkLog parent) { this.parent = parent; } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (this.isVisible() && !isVisibleToUser) { if(parent != null) { parent.invalidateOptionsMenu(); } } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); listData = new LinkedList<ListItem>(); listDataBuffer = new LinkedList<ListItem>(); listDataUnfiltered = new LinkedList<ListItem>(); adapter = new CustomAdapter(getActivity().getApplicationContext(), R.layout.logitem, listData); if(NetworkLog.settings == null) { NetworkLog activity = (NetworkLog) getActivity(); if(activity != null) { activity.loadSettings(); } } try { maxLogEntries = NetworkLog.settings.getMaxLogEntries(); } catch (Exception e) { Log.w("NetworkLog", "Exception getting max log entries: " + e.getMessage(), e); maxLogEntries = 100000; } MyLog.d("LogFragment onCreate"); } @Override public void onDestroy() { super.onDestroy(); MyLog.d("LogFragment onDestroy"); } @Override public void onDestroyView() { super.onDestroyView(); MyLog.d("LogFragment onDestroyView"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { MyLog.d("[LogFragment] onCreateView"); LinearLayout layout = new LinearLayout(getActivity().getApplicationContext()); layout.setOrientation(LinearLayout.VERTICAL); ListView listView = new ListView(getActivity().getApplicationContext()); listView.setAdapter(adapter); listView.setTextFilterEnabled(true); listView.setFastScrollEnabled(true); listView.setSmoothScrollbarEnabled(false); listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL); listView.setStackFromBottom(true); listView.setOnItemClickListener(new CustomOnItemClickListener()); layout.addView(listView); registerForContextMenu(listView); startUpdater(); return layout; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getActivity().getMenuInflater(); inflater.inflate(R.layout.log_context_menu, menu); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info; ListItem listItem; switch(item.getItemId()) { case R.id.log_copy_src_ip: info = (AdapterContextMenuInfo) item.getMenuInfo(); listItem = listData.get(info.position); copySourceIp(listItem); return true; case R.id.log_copy_dst_ip: info = (AdapterContextMenuInfo) item.getMenuInfo(); listItem = listData.get(info.position); copyDestIp(listItem); return true; case R.id.log_graph: info = (AdapterContextMenuInfo) item.getMenuInfo(); listItem = listData.get(info.position); showGraph(listItem); return true; default: return super.onContextItemSelected(item); } } @SuppressWarnings("deprecation") public void copySourceIp(ListItem item) { String srcAddr; String srcPort; if(NetworkLog.resolveHosts && NetworkLog.resolveCopies) { String resolved = NetworkLog.resolver.resolveAddress(item.srcAddr); if(resolved != null) { srcAddr = resolved; } else { srcAddr = item.srcAddr; } } else { srcAddr = item.srcAddr; } if(NetworkLog.resolvePorts && NetworkLog.resolveCopies) { srcPort = NetworkLog.resolver.resolveService(String.valueOf(item.srcPort)); } else { srcPort = String.valueOf(item.srcPort); } ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); /* newer API 11 clipboard unsupported on older devices ClipData clip = ClipData.newPlainText("NetworkLog Source IP", srcAddr + ":" + srcPort); clipboard.setPrimaryClip(clip); */ /* use older deprecated ClipboardManager to support older devices */ clipboard.setText(srcAddr + ":" + srcPort); } @SuppressWarnings("deprecation") public void copyDestIp(ListItem item) { String dstAddr; String dstPort; if(NetworkLog.resolveHosts && NetworkLog.resolveCopies) { String resolved = NetworkLog.resolver.resolveAddress(item.dstAddr); if(resolved != null) { dstAddr = resolved; } else { dstAddr = item.dstAddr; } } else { dstAddr = item.dstAddr; } if(NetworkLog.resolvePorts && NetworkLog.resolveCopies) { dstPort = NetworkLog.resolver.resolveService(String.valueOf(item.dstPort)); } else { dstPort = String.valueOf(item.dstPort); } ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); /* newer API 11 clipboard unsupported on older devices ClipData clip = ClipData.newPlainText("NetworkLog Dest IP", dstAddr + ":" + dstPort); clipboard.setPrimaryClip(clip); */ /* use older deprecated ClipboardManager to support older devices */ clipboard.setText(dstAddr + ":" + dstPort); } public void showGraph(ListItem item) { startActivity(new Intent(getActivity().getApplicationContext(), AppTimelineGraph.class) .putExtra("app_uid", item.app.uid) .putExtra("src_addr", item.srcAddr) .putExtra("src_port", item.srcPort) .putExtra("dst_addr", item.dstAddr) .putExtra("dst_port", item.dstPort)); } private class CustomOnItemClickListener implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { showGraph(listData.get(position)); } } public void startUpdater() { if(updater != null) { updater.stop(); } updater = new ListViewUpdater(); new Thread(updater, "LogFragmentUpdater").start(); } public void onNewLogEntry(final LogEntry entry) { if(listDataBuffer == null) { return; } if(!entry.isValid()) { return; } ApplicationsTracker.AppEntry appEntry = ApplicationsTracker.uidMap.get(entry.uidString); if(appEntry == null) { if(MyLog.enabled) { MyLog.d("LogFragment: No appEntry for uid " + entry.uid); } return; } final ListItem item = new ListItem(appEntry); item.in = entry.in; item.out = entry.out; item.srcAddr = entry.src; item.srcPort = entry.spt; item.dstAddr = entry.dst; item.dstPort = entry.dpt; item.proto = entry.proto; item.len = entry.len; item.timestamp = entry.timestamp; if(MyLog.enabled) { MyLog.d("LogFragment: NewLogEntry: [" + item.app.uidString + "] in=" + item.in + " out=" + item.out + " " + item.srcAddr + ":" + item.srcPort + " --> " + item.dstAddr + ":" + item.dstPort + " proto=" + item.proto + " len=" + item.len); } synchronized(listDataBuffer) { listDataBuffer.add(item); while(listDataBuffer.size() > maxLogEntries) { if(MyLog.enabled) { MyLog.d("Log buffer size reached maxLogEntries limit; truncating"); } listDataBuffer.removeFirst(); } } } public void clearLogEntriesOlderThan(long timerange) { MyLog.d("Clearing logFragment entries older than " + timerange); // Add any items in listDataBuffer to listDataUnfiltered synchronized(listDataBuffer) { synchronized(listDataUnfiltered) { for(ListItem item : listDataBuffer) { if(MyLog.enabled) { MyLog.d("Adding buffer item " + item); } listDataUnfiltered.add(item); } listDataBuffer.clear(); } } long timestamp = System.currentTimeMillis() - timerange; MyLog.d("Setting timestamp " + timestamp); // Remove items older than timerange synchronized(listDataUnfiltered) { Iterator<ListItem> iterator = listDataUnfiltered.iterator(); while(iterator.hasNext()) { ListItem item = iterator.next(); if(MyLog.enabled) { MyLog.d("Checking item " + item.app.uid + " " + item.app.name + " " + item.timestamp); } if(item.timestamp < timestamp) { if(MyLog.enabled) { MyLog.d("Removing item"); } iterator.remove(); } else { // remaining entries should be >= timestamp break; } } synchronized(listData) { listData.clear(); listData.addAll(listDataUnfiltered); } } NetworkLog.handler.post(new Runnable() { public void run() { if(NetworkLog.filterTextInclude.length() > 0 || NetworkLog.filterTextExclude.length() > 0) { setFilter(""); } else { refreshAdapter(); } } }); } public void pruneLogEntries() { synchronized(listDataBuffer) { while(listDataBuffer.size() > maxLogEntries) { listDataBuffer.removeFirst(); } } synchronized(listDataUnfiltered) { while(listDataUnfiltered.size() > maxLogEntries) { listDataUnfiltered.removeFirst(); } } synchronized(listData) { while(listData.size() > maxLogEntries) { listData.removeFirst(); } refreshAdapter(); } } public void stopUpdater() { if(updater != null) { updater.stop(); } } public boolean appFragmentNeedsRebuild = false; Runnable updaterRunner = new Runnable() { public void run() { if(MyLog.enabled) { MyLog.d("LogFragmentUpdater enter"); } if(listDataBuffer == null || listData == null || listDataUnfiltered == null) { return; } int i = 0; boolean included = true; boolean excluded = false; long start = System.currentTimeMillis(); synchronized(listDataBuffer) { synchronized(listData) { synchronized(listDataUnfiltered) { for(ListItem item : listDataBuffer) { if(NetworkLog.filterTextInclude.length() > 0) { included = testIncludeFilter(item); } if(NetworkLog.filterTextExclude.length() > 0) { excluded = testExcludeFilter(item); } if(included == true && excluded == false) { listData.add(item); } listDataUnfiltered.add(item); i++; } listDataBuffer.clear(); } } } synchronized(listDataUnfiltered) { while(listDataUnfiltered.size() > maxLogEntries) { listDataUnfiltered.removeFirst(); } } synchronized(listData) { while(listData.size() > maxLogEntries) { listData.removeFirst(); } } refreshAdapter(); long elapsed = System.currentTimeMillis() - start; if(MyLog.enabled) { MyLog.d("LogFragmentUpdater exit: added " + i + " items -- elapsed: " + elapsed); } if(appFragmentNeedsRebuild) { appFragmentNeedsRebuild = false; NetworkLog.appFragment.rebuildLogEntries(); NetworkLog.appFragment.updaterRunOnce(); } } }; public void updaterRunOnce() { NetworkLog.handler.post(updaterRunner); } // todo: this is largely duplicated in AppFragment -- move to its own file private class ListViewUpdater implements Runnable { boolean running = false; public void stop() { running = false; } public void run() { running = true; MyLog.d("Starting LogFragmentUpdater " + this); while(running) { if(needsRefresh == true || (listDataBuffer != null && listDataBuffer.size() > 0)) { updaterRunOnce(); needsRefresh = false; } try { Thread.sleep(1000); } catch(Exception e) { Log.d("NetworkLog", "LogFragmentListUpdater", e); } } if(MyLog.enabled) { MyLog.d("Stopped LogFragment updater " + this); } } } public void setFilter(CharSequence s) { // MyLog.d("[LogFragment] setFilter(" + s + ")"); if(adapter != null) { adapter.getFilter().filter(s); } } String srcAddrResolved; String srcPortResolved; String dstAddrResolved; String dstPortResolved; String iface; boolean matched; public boolean testIncludeFilter(ListItem item) { matched = false; if(NetworkLog.resolveHosts) { srcAddrResolved = NetworkLog.resolver.resolveAddress(item.srcAddr); if(srcAddrResolved == null) { srcAddrResolved = ""; } dstAddrResolved = NetworkLog.resolver.resolveAddress(item.dstAddr); if(dstAddrResolved == null) { dstAddrResolved = ""; } } else { srcAddrResolved = ""; dstAddrResolved = ""; } if(NetworkLog.resolvePorts) { srcPortResolved = NetworkLog.resolver.resolveService(String.valueOf(item.srcPort)); dstPortResolved = NetworkLog.resolver.resolveService(String.valueOf(item.dstPort)); } else { srcPortResolved = ""; dstPortResolved = ""; } if(item.in != null && item.in.length() > 0) { iface = item.in; } else { iface = item.out; } for(String c : NetworkLog.filterTextIncludeList) { if((NetworkLog.filterNameInclude && item.app.nameLowerCase.contains(c)) || (NetworkLog.filterUidInclude && item.app.uidString.equals(c)) || (NetworkLog.filterAddressInclude && ((item.srcAddr.contains(c) || StringPool.getLowerCase(srcAddrResolved).contains(c)) || (item.dstAddr.contains(c) || StringPool.getLowerCase(dstAddrResolved).contains(c)))) || (NetworkLog.filterPortInclude && ((String.valueOf(item.srcPort).equals(c) || StringPool.getLowerCase(srcPortResolved).equals(c)) || (String.valueOf(item.dstPort).equals(c) || StringPool.getLowerCase(dstPortResolved).equals(c)))) || (NetworkLog.filterInterfaceInclude && iface.contains(c)) || (NetworkLog.filterProtocolInclude && (item.proto.equals(c) || StringPool.getLowerCase(NetworkLog.resolver.resolveProtocol(item.proto)).equals(c)))) { matched = true; break; } } return matched; } boolean testExcludeFilter(ListItem item) { matched = false; if(NetworkLog.resolveHosts) { srcAddrResolved = NetworkLog.resolver.resolveAddress(item.srcAddr); if(srcAddrResolved == null) { srcAddrResolved = ""; } dstAddrResolved = NetworkLog.resolver.resolveAddress(item.dstAddr); if(dstAddrResolved == null) { dstAddrResolved = ""; } } else { srcAddrResolved = ""; dstAddrResolved = ""; } if(NetworkLog.resolvePorts) { srcPortResolved = NetworkLog.resolver.resolveService(String.valueOf(item.srcPort)); // fixme: get from stringpool dstPortResolved = NetworkLog.resolver.resolveService(String.valueOf(item.dstPort)); // fixme: get from stringpool } else { srcPortResolved = ""; dstPortResolved = ""; } if(item.in != null && item.in.length() > 0) { iface = item.in; } else { iface = item.out; } for(String c : NetworkLog.filterTextExcludeList) { if((NetworkLog.filterNameExclude && item.app.nameLowerCase.contains(c)) || (NetworkLog.filterUidExclude && item.app.uidString.equals(c)) || (NetworkLog.filterAddressExclude && ((item.srcAddr.contains(c) || StringPool.getLowerCase(srcAddrResolved).contains(c)) || (item.dstAddr.contains(c) || StringPool.getLowerCase(dstAddrResolved).contains(c)))) || (NetworkLog.filterPortExclude && ((String.valueOf(item.srcPort).equals(c) || StringPool.getLowerCase(srcPortResolved).equals(c)) || (String.valueOf(item.dstPort).equals(c) || StringPool.getLowerCase(dstPortResolved).equals(c)))) || (NetworkLog.filterInterfaceExclude && iface.contains(c)) || (NetworkLog.filterProtocolExclude && (item.proto.equals(c) || StringPool.getLowerCase(NetworkLog.resolver.resolveProtocol(item.proto)).equals(c)))) { matched = true; break; } } return matched; } private class CustomAdapter extends ArrayAdapter<ListItem> implements Filterable { LayoutInflater mInflater = (LayoutInflater) getActivity().getSystemService(Activity.LAYOUT_INFLATER_SERVICE); CustomFilter filter; public CustomAdapter(Context context, int resource, List<ListItem> objects) { super(context, resource, objects); } private class CustomFilter extends Filter { FilterResults results = new FilterResults(); @Override protected FilterResults performFiltering(CharSequence constraint) { ArrayList<ListItem> originalItems = new ArrayList<ListItem>(listDataUnfiltered.size()); ArrayList<ListItem> filteredItems = new ArrayList<ListItem>(listDataUnfiltered.size()); int[] includedItemsIndex = new int[listDataUnfiltered.size()]; int includedItemsPos = 0; int iteratorPos = -1; ListItem item; doNotRefresh = true; if(MyLog.enabled) { MyLog.d("[LogFragment] performFiltering"); } synchronized(listDataUnfiltered) { originalItems.addAll(listDataUnfiltered); } if(NetworkLog.filterTextInclude.length() == 0 && NetworkLog.filterTextExclude.length() == 0) { MyLog.d("[LogFragment] no constraint item count: " + originalItems.size()); results.values = originalItems; results.count = originalItems.size(); } else { if(MyLog.enabled) { MyLog.d("[LogFragment] item count: " + originalItems.size()); } if(NetworkLog.filterTextIncludeList.size() > 0) { Iterator<ListItem> iterator = originalItems.iterator(); while(iterator.hasNext()) { item = iterator.next(); iteratorPos++; if(MyLog.enabled) { MyLog.d("[LogFragment] testing filtered item " + item + "; includes: [" + NetworkLog.filterTextInclude + "]"); } matched = testIncludeFilter(item); if(matched) { if(MyLog.enabled) { MyLog.d("[LogFragment] adding filtered item " + item); } includedItemsIndex[includedItemsPos++] = iteratorPos; } } } else { int count = originalItems.size(); for(int i = 0; i < count; i++) { includedItemsIndex[includedItemsPos++] = i; } } if(NetworkLog.filterTextExcludeList.size() > 0) { for(int i = 0; i < includedItemsPos; i++) { item = originalItems.get(includedItemsIndex[i]); if(MyLog.enabled) { MyLog.d("[LogFragment] testing filtered item " + item + "; excludes: [" + NetworkLog.filterTextExclude + "]"); } matched = testExcludeFilter(item); if(matched) { if(MyLog.enabled) { MyLog.d("[LogFragment] excluding filtered item " + item); } } else { filteredItems.add(item); } } } else { // no exclusion filter, add all included items to filteredItems for(int i = 0; i < includedItemsPos; i++) { filteredItems.add(originalItems.get(includedItemsIndex[i])); } } results.values = filteredItems; results.count = filteredItems.size(); } if(MyLog.enabled) { MyLog.d("[LogFragment] filter returning " + results.count + " items"); } return results; } @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence constraint, FilterResults results) { if(MyLog.enabled) { MyLog.d("[LogFragment] Publishing filter results"); } synchronized(listData) { listData.clear(); listData.addAll((ArrayList<ListItem>) results.values); if(MyLog.enabled) { MyLog.d("[LogFilter] listdata size after filter: " + listData.size()); } } doNotRefresh = false; refreshAdapter(); } } @Override public CustomFilter getFilter() { if(filter == null) { filter = new CustomFilter(); } return filter; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; ImageView icon; TextView name; TextView iface; final TextView srcAddr; TextView srcPort; final TextView dstAddr; TextView dstPort; TextView len; TextView timestamp; final ListItem item = getItem(position); if(convertView == null) { convertView = mInflater.inflate(R.layout.logitem, null); holder = new ViewHolder(convertView); convertView.setTag(holder); } holder = (ViewHolder) convertView.getTag(); icon = holder.getIcon(); icon.setTag(item.app.packageName); icon.setImageDrawable(ApplicationsTracker.loadIcon(getActivity().getApplicationContext(), icon, item.app.packageName)); name = holder.getName(); name.setText("(" + item.app.uid + ")" + " " + item.app.name); iface = holder.getInterface(); String proto; if(item.proto != null && item.proto.length() > 0) { proto = NetworkLog.resolver.resolveProtocol(item.proto) + "/"; } else { proto = ""; } if(item.in != null && item.in.length() != 0) { iface.setText(proto + item.in); } else { iface.setText(proto + item.out); } srcAddr = holder.getSrcAddr(); srcAddr.setTag(item.srcAddr); if(NetworkLog.resolveHosts) { String resolved = NetworkLog.resolver.getResolvedAddress(item.srcAddr); if(resolved == null) { NetworkResolverUpdater updater = new NetworkResolverUpdater() { public void run() { String tag = (String) srcAddr.getTag(); if(tag != null && tag.equals(item.srcAddr)) { srcAddr.setText("SRC: " + resolved); } } }; resolved = NetworkLog.resolver.resolveAddress(item.srcAddr, updater); } if(resolved != null) { srcAddr.setText("SRC: " + resolved); } else { srcAddr.setText("SRC: " + item.srcAddr); } } else { srcAddr.setText("SRC: " + item.srcAddr); } srcPort = holder.getSrcPort(); if(NetworkLog.resolvePorts) { srcPort.setText(NetworkLog.resolver.resolveService(String.valueOf(item.srcPort))); } else { srcPort.setText(String.valueOf(item.srcPort)); } dstAddr = holder.getDstAddr(); dstAddr.setTag(item.dstAddr); if(NetworkLog.resolveHosts) { String resolved = NetworkLog.resolver.getResolvedAddress(item.dstAddr); if(resolved == null) { NetworkResolverUpdater updater = new NetworkResolverUpdater() { public void run() { String tag = (String) dstAddr.getTag(); if(tag != null && tag.equals(item.dstAddr)) { dstAddr.setText("DST: " + resolved); } } }; resolved = NetworkLog.resolver.resolveAddress(item.dstAddr, updater); } if(resolved != null) { dstAddr.setText("DST: " + resolved); } else { dstAddr.setText("DST: " + item.dstAddr); } } else { dstAddr.setText("DST: " + item.dstAddr); } dstPort = holder.getDstPort(); if(NetworkLog.resolvePorts) { dstPort.setText(NetworkLog.resolver.resolveService(String.valueOf(item.dstPort))); } else { dstPort.setText(String.valueOf(item.dstPort)); } len = holder.getLen(); len.setText("LEN: " + item.len); timestamp = holder.getTimestamp(); timestamp.setText(Timestamp.getTimestamp(item.timestamp)); return convertView; } } private class ViewHolder { private View mView; private ImageView mIcon = null; private TextView mName = null; private TextView mInterface = null; private TextView mSrcAddr = null; private TextView mSrcPort = null; private TextView mDstAddr = null; private TextView mDstPort = null; private TextView mLen = null; private TextView mTimestamp = null; public ViewHolder(View view) { mView = view; } public ImageView getIcon() { if(mIcon == null) { mIcon = (ImageView) mView.findViewById(R.id.logIcon); } return mIcon; } public TextView getName() { if(mName == null) { mName = (TextView) mView.findViewById(R.id.logName); } return mName; } public TextView getInterface() { if(mInterface == null) { mInterface = (TextView) mView.findViewById(R.id.logInterface); } return mInterface; } public TextView getSrcAddr() { if(mSrcAddr == null) { mSrcAddr = (TextView) mView.findViewById(R.id.srcAddr); } return mSrcAddr; } public TextView getSrcPort() { if(mSrcPort == null) { mSrcPort = (TextView) mView.findViewById(R.id.srcPort); } return mSrcPort; } public TextView getDstAddr() { if(mDstAddr == null) { mDstAddr = (TextView) mView.findViewById(R.id.dstAddr); } return mDstAddr; } public TextView getDstPort() { if(mDstPort == null) { mDstPort = (TextView) mView.findViewById(R.id.dstPort); } return mDstPort; } public TextView getLen() { if(mLen == null) { mLen = (TextView) mView.findViewById(R.id.len); } return mLen; } public TextView getTimestamp() { if(mTimestamp == null) { mTimestamp = (TextView) mView.findViewById(R.id.timestamp); } return mTimestamp; } } }
package org.mousephenotype.cda.loads.dccimport.imits; import org.mousephenotype.cda.db.utilities.SqlUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import javax.sql.DataSource; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Imits client that uses a report from iMits to get approprate data * <p> * Fields in the internal database are: symbol, accession, colony, escell, strain, production_center, project, center, * resource, allele */ public class FileBasedImitsClient implements ImitsClient { private static final Logger logger = LoggerFactory.getLogger(FileBasedImitsClient.class); private static boolean initialized = false; public Map<String, String> centerNameMap = new HashMap<>(); private DataSource dataSource; private JdbcTemplate jdbc; public FileBasedImitsClient(String filename) throws IOException, SQLException { // Set up the database initDb(); // Setup the center name map centerNameMap.put("HARWELL", "MRC HARWELL"); centerNameMap.put("RIKEN BRC", "RBRC"); if (filename == null || !Files.exists(Paths.get(filename))) { throw new RuntimeException("Filename must be defined and exist."); } String output = new String(Files.readAllBytes(Paths.get(filename))); // Parse the file into the embedded db for (String line : output.split("\n")) { insert(line); } String sql = "SELECT DISTINCT COUNT(*) FROM colony"; Integer c = jdbc.queryForObject(sql, Integer.class); logger.debug("Loaded {} lines", c); } private DataSource dataSource() { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); return builder.setType(EmbeddedDatabaseType.HSQL).build(); } public JdbcTemplate getJdbc() { dataSource = dataSource(); return new JdbcTemplate(dataSource); } private void initDb() { // Set up the jdbc template jdbc = getJdbc(); if (!initialized) { jdbc.execute("CREATE TABLE colony (symbol VARCHAR(255), accession VARCHAR(255), colony VARCHAR(255), escell VARCHAR(255), strain VARCHAR(255), production_center VARCHAR(255), project VARCHAR(255), center VARCHAR(255), resource VARCHAR(255), allele VARCHAR(255))"); initialized = true; } else { jdbc.execute("DELETE FROM colony"); } } private void insert(String s) throws SQLException { String sql = "INSERT INTO colony (symbol, accession, colony, escell, strain, production_center, project, center, resource, allele) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(sql)) { int i = 1; for (String field : Arrays.asList(s.split("\t"))) { // Translate the organisation names from iMits names to CDA names if (i == 6 || i == 8) { SqlUtils.setSqlParameter(statement, getCenterName(field), i++); } else { SqlUtils.setSqlParameter(statement, field, i++); } } statement.executeUpdate(); } } public String getCenterName(String orgName) { String upperOrgName = orgName.toUpperCase(); if (centerNameMap.containsKey(upperOrgName)) { upperOrgName = centerNameMap.get(upperOrgName); } return upperOrgName; } @Override public String getGeneByColonyId(String colonyId, String center) { String sql = "SELECT DISTINCT accession FROM colony WHERE colony=? AND center=?"; logger.debug("Executing sql " + sql); try { return jdbc.queryForObject(sql, new Object[]{colonyId, center.toUpperCase()}, String.class); } catch (EmptyResultDataAccessException e) { return null; } } @Override public String getAlleleSymbolByColonyId(String colonyId) { String sql = "SELECT DISTINCT allele FROM colony WHERE colony=?";//" '" + colonyId + "'"; logger.debug("Executing sql " + sql); try { return jdbc.queryForObject(sql, new Object[]{colonyId}, String.class); } catch (EmptyResultDataAccessException e) { return null; } } @Override public String getStrainByColonyId(String colonyId, String center) { String sql = "SELECT DISTINCT strain FROM colony WHERE colony=? AND center=?"; logger.debug("Executing sql " + sql); try { return jdbc.queryForObject(sql, new Object[]{colonyId, center.toUpperCase()}, String.class); } catch (EmptyResultDataAccessException e) { return null; } } @Override public String getStrainNameByColonyId(String colonyId, String center) { return this.getStrainByColonyId(colonyId, center); } @Override public String getColonyIdByEsCell(String escell, String center) { String sql = "SELECT DISTINCT colony FROM colony WHERE escell=? AND center=? ORDER BY colony LIMIT 1"; logger.debug("Executing sql " + sql); try { return jdbc.queryForObject(sql, new Object[]{escell, center.toUpperCase()}, String.class); } catch (EmptyResultDataAccessException e) { return null; } } @Override public String getProjectByEsCell(String escell, String center) { String sql = "SELECT DISTINCT project FROM colony WHERE escell=? AND center=?"; logger.debug("Executing sql " + sql); try { return jdbc.queryForObject(sql, new Object[]{escell, center.toUpperCase()}, String.class); } catch (IncorrectResultSizeDataAccessException e) { // If there are more than one project for this escell/center combination // and if the projects are "MGP" and "MGP Legacy". // Only in legacy data is project looked up by ESCell // Detect this and pass back appropriately List<String> projects = jdbc.query(sql, new RowMapper<String>() { public String mapRow(ResultSet rs, int rowNum) throws SQLException { return rs.getString(1); } }, escell, center.toUpperCase()); // This is a legacy line and so we will return "MGP Legacy" if (projects.size()>0 && projects.contains("MGP") && projects.contains("MGP Legacy")) { return "MGP Legacy"; } return null; } } @Override public String getAlleleMGIIDByEscell(String esCell) { logger.debug("getAlleleMGIIDByEscell is not implemented for File Based Imits client."); return null; } @Override public String getGeneByEscell(String escell) { String sql = "SELECT DISTINCT accession FROM colony WHERE escell=?"; logger.debug("Executing sql " + sql); try { return jdbc.queryForObject(sql, new Object[]{escell}, String.class); } catch (EmptyResultDataAccessException e) { return null; } } }
package com.itlaborer.apitools.ui; import java.io.File; import java.io.IOException; import java.util.ArrayList; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import com.alibaba.fastjson.JSON; import com.itlaborer.apitools.model.ApiDoc; import com.itlaborer.apitools.model.ApiItem; import com.itlaborer.apitools.model.ApiList; import com.itlaborer.apitools.model.ApiPar; import com.itlaborer.apitools.res.Resource; import com.itlaborer.apitools.swt.SWTResourceManager; import com.itlaborer.apitools.utils.ApiUtils; import com.itlaborer.apitools.utils.JsonFormatUtils; /** * API * @author liudewei[793554262@qq.com] * @version 1.0 * @since 1.0 */ public class CovertTools extends Dialog { private static Logger logger = Logger.getLogger(CovertTools.class.getName()); protected Object result; protected Shell covertToolsShell; private Text filePath; private File path; private Text setNameText; private Button saveButton; private Text apiDocVersion; private String apiDocJson; private Label apiDocVersionl; private Combo versionSelect; private int versionSelectint; private Text statusText; public CovertTools(Shell parent, int style) { super(parent, style); this.setText("API"); this.path = null; this.apiDocJson = ""; versionSelectint = 4; } public Object open() { createContents(); covertToolsShell.open(); covertToolsShell.layout(); Display display = getParent().getDisplay(); while (!covertToolsShell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } return result; } private void createContents() { covertToolsShell = new Shell(getParent(), getStyle()); covertToolsShell.setImage(SWTResourceManager.getImage(CovertTools.class, Resource.IMAGE_ICON)); covertToolsShell.setSize(400, 180); covertToolsShell.setText(getText()); ApiUtils.SetCenterinParent(getParent(), covertToolsShell); filePath = new Text(covertToolsShell, SWT.BORDER); filePath.setBounds(10, 12, 230, 25); Button fileSelect = new Button(covertToolsShell, SWT.NONE); fileSelect.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { FileDialog fd = new FileDialog(covertToolsShell, SWT.OPEN); fd.setFilterExtensions(new String[] { "*.html;*.chm", "*.*" }); fd.setFilterNames(new String[] { "HTML(*.html)/CHM(*.chm)", "All Files(*.*)" }); String file = fd.open(); if (StringUtils.isNotEmpty(file)) { path = new File(file); filePath.setText(path.getPath()); } } }); fileSelect.setBounds(311, 11, 73, 27); fileSelect.setText(""); final Button beginCovert = new Button(covertToolsShell, SWT.NONE); beginCovert.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (null == path) { logger.info("API"); statusText.setText("API"); return; } else if (StringUtils.isEmpty(apiDocVersion.getText())) { logger.info("API"); statusText.setText("API"); return; } logger.info("" + path.getPath()); beginCovert.setText(""); beginCovert.setEnabled(false); saveButton.setEnabled(false); statusText.setText("" + path.getPath()); setNameText.setText("fundapi-" + apiDocVersion.getText() + ".json"); final String version = apiDocVersion.getText(); new Thread() { public void run() { // UI,UI apiDocJson = CovertApiDoc(version); // UIUI,UI getParent().getDisplay().syncExec(new Thread() { public void run() { if (apiDocJson == null) { beginCovert.setEnabled(true); beginCovert.setText(""); saveButton.setEnabled(true); logger.info("," + versionSelect.getText() + ""); statusText.setText("," + versionSelect.getText() + ""); } else { beginCovert.setEnabled(true); beginCovert.setText(""); saveButton.setEnabled(true); logger.info(""); statusText.setText(","); } } }); } }.start(); } }); beginCovert.setText(""); beginCovert.setBounds(249, 52, 135, 27); setNameText = new Text(covertToolsShell, SWT.BORDER); setNameText.setBounds(106, 92, 134, 25); Label setName = new Label(covertToolsShell, SWT.NONE); setName.setFont(SWTResourceManager.getFont("", 13, SWT.NORMAL)); setName.setBounds(10, 92, 90, 25); setName.setText(""); saveButton = new Button(covertToolsShell, SWT.NONE); saveButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (setNameText.getText() == "") { statusText.setText(""); return; } if (apiDocJson.equals("")) { logger.info(""); statusText.setText(""); return; } if (ApiUtils.SaveToFile(new File("./config/" + setNameText.getText()), apiDocJson)) { statusText.setText("config.properties"); } else { statusText.setText(""); } } }); saveButton.setBounds(249, 91, 135, 27); saveButton.setText(""); apiDocVersion = new Text(covertToolsShell, SWT.BORDER); apiDocVersion.setBounds(106, 53, 134, 25); apiDocVersionl = new Label(covertToolsShell, SWT.NONE); apiDocVersionl.setText(" "); apiDocVersionl.setFont(SWTResourceManager.getFont("", 13, SWT.NORMAL)); apiDocVersionl.setBounds(10, 54, 90, 25); versionSelect = new Combo(covertToolsShell, SWT.NONE | SWT.READ_ONLY); versionSelect.setBounds(249, 12, 60, 25); versionSelect.add("API4.0"); versionSelect.select(0); statusText = new Text(covertToolsShell, SWT.BORDER); statusText.setBounds(10, 121, 374, 23); } public String CovertApiDoc(String apiDocVersion) { // ApiDoc ApiDoc apiDoc = new ApiDoc(); apiDoc.setApi_version(apiDocVersion); apiDoc.setDecode_version("1.0"); // html if (path.getPath().substring(path.getPath().lastIndexOf(".") + 1).equals("html") || path.getPath().substring(path.getPath().lastIndexOf(".") + 1).equals("HTML") || path.getPath().substring(path.getPath().lastIndexOf(".") + 1).equals("htm") || path.getPath().substring(path.getPath().lastIndexOf(".") + 1).equals("HTM")) { logger.info("html"); // index.htmlhtmlindex.html, if (new File(path.getParent() + "/html/index.html").exists()) { apiDoc.setApilist(CovertApilist(path.getParent() + "/html/index.html")); } else { apiDoc.setApilist(CovertApilist(path.getPath())); } // chm,chmhhwindows } else if (path.getPath().substring(path.getPath().lastIndexOf(".") + 1).equals("chm") || path.getPath().substring(path.getPath().lastIndexOf(".") + 1).equals("CHM")) { logger.info("chm,Windows"); // chm // tmp File tmp = new File("./tmp"); if (tmp.exists()) { ApiUtils.DeleteDir(tmp); } else { tmp.mkdir(); } // hh.exe Runtime rn = Runtime.getRuntime(); try { String command = "hh.exe -decompile " + "./tmp " + path.getPath(); Process process = rn.exec(command); process.waitFor(); apiDoc.setApilist(CovertApilist(tmp.getPath() + "/index.html")); ApiUtils.DeleteDir(tmp); } catch (Exception e) { logger.info("", e); } } else { logger.info(""); } return (JsonFormatUtils.Format(JSON.toJSONString(apiDoc))); } /** * API-- * */ public ArrayList<ApiList> CovertApilist(String indexPath) { logger.info("" + indexPath); ArrayList<ApiList> apiList = new ArrayList<ApiList>(); try { Document document = Jsoup.parse(new File(indexPath), "UTF-8"); Elements div_ul = document.body().children(); for (int i = 0; i < div_ul.size(); i++) { if (div_ul.get(i).tagName().equals("div")) { ApiList thisTypeApiList = new ApiList(); ArrayList<String> apiHTMLPath = new ArrayList<String>(); thisTypeApiList.setName(div_ul.get(i).text()); for (int r = 0; r < div_ul.get(i + 1).children().size(); r++) { String path = new File(indexPath).getParent() + "/" + div_ul.get(i + 1).child(r).child(0).attr("href"); logger.info(path); apiHTMLPath.add(path); } if (versionSelectint == 4) { logger.info("API4.0"); thisTypeApiList.setApi(CovertApi4(apiHTMLPath)); } if (thisTypeApiList.getApi().size() > 0) { apiList.add(thisTypeApiList); } } } } catch (IOException e) { logger.error("", e); } return apiList; } /** * API API4.0 */ public ArrayList<ApiItem> CovertApi4(ArrayList<String> apiHTMLPath) { ArrayList<ApiItem> apiItems = new ArrayList<ApiItem>(); for (int i = 0; i < apiHTMLPath.size(); i++) { logger.info("" + apiHTMLPath.get(i)); ApiItem apiItem = new ApiItem(); try { // HTML Document document = Jsoup.parse(new File(apiHTMLPath.get(i)), "UTF-8"); Elements tables = document.getElementsByTag("table"); // 6table if (tables.size() == 6) { apiItem.setName(tables.get(1).child(0).child(0).child(1).text()); try { apiItem.setAddress(tables.get(1).child(0).child(1).child(1).text().substring(23) .replaceAll("\\(.*?\\)|\\{.*?}|\\[.*?]|.*?", "").trim()); } catch (StringIndexOutOfBoundsException e) { apiItem.setAddress(""); logger.error("", e); } ArrayList<ApiPar> pars = new ArrayList<ApiPar>(); try { Elements parsrow = tables.get(2).getElementsByTag("tr"); if (parsrow != null) { int n1 = Integer.parseInt(parsrow.get(1).child(1).attr("rowspan")); for (int i1 = 0; i1 < n1; i1++) { ApiPar par = new ApiPar(); if (i1 == 0) { par.setName(parsrow.get(i1 + 1).child(2).text()); par.setTip(parsrow.get(i1 + 1).child(3).text()); par.setValue(parsrow.get(i1 + 1).child(9).text() + ""); } else { par.setName(parsrow.get(i1 + 1).child(1).text()); par.setTip(parsrow.get(i1 + 1).child(2).text()); par.setValue(parsrow.get(i1 + 1).child(8).text() + ""); } pars.add(par); } } apiItem.setParameters(pars); } catch (Exception e) { logger.info(""); logger.error("", e); } } else { continue; } } catch (Exception e) { logger.info(""); logger.error("", e); continue; } apiItems.add(apiItem); } return apiItems; } }
package com.jorgediaz.util.model; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.service.BaseLocalService; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; public class ModelFactory { public ModelFactory() { this(null, null); } public ModelFactory(Class<? extends Model> defaultModelClass) { this(defaultModelClass, null); } public ModelFactory( Class<? extends Model> defaultModelClass, Map<String, Class<? extends Model>> modelClassMap) { if (defaultModelClass == null) { this.defaultModelClass = DefaultModel.class; } else { this.defaultModelClass = defaultModelClass; } this.modelClassMap = modelClassMap; } public Map<String, Model> getModelMap(Collection<String> classNames) { ClassLoader classLoader = ModelUtil.getClassLoader(); Map<String, Model> modelMap = new LinkedHashMap<String, Model>(); for (String classname : classNames) { if (Validator.isNull(classname) || !classname.contains(".model.")) { continue; } Model model = null; String[] attributes = null; try { model = this.getModelObject(classLoader, classname); if (model != null) { attributes = model.getAttributesName(); } } catch (Exception e) { if (_log.isDebugEnabled()) { _log.debug(e, e); } else if (_log.isInfoEnabled()) { _log.info( "Cannot get model object of " + classname + " EXCEPTION: " + e.getClass().getName() + ": " + e.getMessage()); } } if ((model != null) && (attributes != null)) { modelMap.put(model.getName(), model); } } return modelMap; } public final Model getModelObject( ClassLoader classLoader, String className) { String classPackageName = StringPool.BLANK; String classSimpleName = className; int pos = className.lastIndexOf("."); if (pos > 0) { classPackageName = className.substring(0, pos); classSimpleName = className.substring(pos + 1, className.length()); } Class<? extends Model> modelClass = this.defaultModelClass; if ((this.modelClassMap != null) && this.modelClassMap.containsKey(className)) { modelClass = this.modelClassMap.get(className); } Model model = null; try { model = (Model)modelClass.newInstance(); BaseLocalService service = reflectionUtil.getService( classLoader, classPackageName, classSimpleName); model.setModelFactory(this); model.init( reflectionUtil, classPackageName, classSimpleName, service); } catch (Exception e) { _log.error( "getModelObject(" + className + ") ERROR " + e.getClass().getName() + ": " + e.getMessage()); throw new RuntimeException(e); } return model; } protected Class<? extends Model> defaultModelClass = null; protected Map<String, Class<? extends Model>> modelClassMap = null; protected ReflectionUtil reflectionUtil = new ReflectionUtil(); private static Log _log = LogFactoryUtil.getLog(ModelFactory.class); }
package com.ninchat.client.model; import com.ninchat.client.transport.AckListener; import com.ninchat.client.transport.actions.LoadHistory; import com.ninchat.client.transport.actions.SendMessage; import com.ninchat.client.transport.actions.UpdateSession; import com.ninchat.client.transport.payloads.MessagePayload; import com.ninchat.client.transport.payloads.NinchatLinkMessage; import com.ninchat.client.transport.payloads.NinchatTextMessage; import java.io.Serializable; import java.util.*; import java.util.concurrent.CopyOnWriteArraySet; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Kari Lavikka */ public abstract class Conversation { private final static Logger logger = Logger.getLogger(Conversation.class.getName()); protected final String id; protected final Session session; protected final Collection<ConversationListener> conversationListeners = new CopyOnWriteArraySet<ConversationListener>(); protected final WrappedId wrappedId; // TODO: Limit history size protected final SortedSet<Message> messages = new TreeSet<Message>(); public static final long DEFAULT_HISTORY_SIZE = 20; protected boolean historyLoaded = false; private String lastSeenMessageId = null; public static final String HIGHLIGHT_TOKEN_SPLITTER = "[\\s\\p{Punct}]"; public enum ActivityStatus { NONE(0), UNREAD(1), HIGHLIGHT(2); private int priority; ActivityStatus(int p) { priority = p; } public int getPriority() { return priority; } } ActivityStatus activityStatus = ActivityStatus.NONE; public Conversation(Session session, String id, WrappedId wrappedId) { this.id = id; this.session = session; this.wrappedId = wrappedId; } public SortedSet<Message> getMessages() { return messages; } /** * Add a batch of messages. This should be used when message history is loaded. ActivityStatus stays intact * because it is assumed that these messages have been written in the past. * * @param messages Messages to add */ void addMessages(List<Message> messages) { boolean hadNew = false; synchronized (this.messages) { hadNew = this.messages.addAll(messages); } if (!messages.isEmpty() && activityStatus == ActivityStatus.NONE) { // Make an assumption that user has seen all updateLastSeenMessageId(messages.get(messages.size() - 1).getId()); } if (logger.isLoggable(Level.FINER))logger.finer("Messages added to chat " + getName()); for (ConversationListener a : conversationListeners) { a.onMessages(this, messages); } } /** * Add a single message. This should be used when a new message is received. * * @param message Message to add */ void addMessage(Message message) { boolean wasNew; synchronized (messages) { wasNew = messages.add(message); } if (logger.isLoggable(Level.FINER))logger.finer("Message added to chat " + getName()); for (ConversationListener a : conversationListeners) { a.onMessage(this, message); } if (message.payloadMatches(NinchatTextMessage.class, NinchatLinkMessage.class)) { // If message was user's own (and sent from another client)... if (session.getUserId().equals(message.getUserId())) { // ... mark all messages automatically as seen. updateLastSeenMessageId(message.getId()); } else if (isNewMessages()) { // A conversationListener may have marked it read already if (containsHighlightTokens(message)) { setActivityStatus(ActivityStatus.HIGHLIGHT); } else { setActivityStatus(ActivityStatus.UNREAD); } } } } /** * Updates last seen message id and calls activity status listeners if activity status changes. */ public void updateLastSeenMessageId() { Message latest; synchronized (messages) { latest = messages.isEmpty() ? null : messages.last(); } if (latest != null) { updateLastSeenMessageId(latest.getId()); } } /** * Updates last seen message id and calls notification listeners if activity status changes. This method * can be used if last seen message is not the latest we have received. Honestly, this probably gets * a bit too over engineered... * * @param messageId */ public void updateLastSeenMessageId(String messageId) { setActivityStatus(ActivityStatus.NONE); // Nah, assume that all messages are seen .. if (lastSeenMessageId != null && messageId.compareTo(lastSeenMessageId) <= 0) return; // No op lastSeenMessageId = messageId; // Send action to server UpdateSession a = new UpdateSession(); a.setMessageId(lastSeenMessageId); if (this instanceof Channel) { a.setChannelId(getId()); } else { assert this instanceof Dialogue; a.setUserId(getId()); } session.getTransport().enqueue(a); // Clear activity status /* SortedSet<Message> tailSet = messages.tailSet(new Message(messageId)); if (tailSet.size() <= 1) { // Latest message have been seen setActivityStatus(ActivityStatus.NONE); } else { // TODO: This doesn't work. It gets complicated if user had new highlights and this update acknowledges them // but some unread messages remain. There's no listener method for that event. // Anyway, we could now iterate remaining messages in tailset and check if they contain highlightable // messages and set activity status accordingly. } */ } public String getLastSeenMessageId() { return lastSeenMessageId; } /** * Returns true if there are (new) unseen messages in this conversation * * @return true if unread */ public boolean isNewMessages() { Message latest; synchronized (messages) { latest = messages.isEmpty() ? null : messages.last(); } if (latest == null) return false; if (lastSeenMessageId == null) return true; return latest.getId().compareTo(lastSeenMessageId) > 0; } public ActivityStatus getActivityStatus() { return activityStatus; } /** * <p>Sets activity status and calls activity status listeners if status was changed.</p> * <p><strong>Note:</strong> it is forbidden to go from HIGHLIGHT to UNREAD. It's just ignored.</p> * * @param activityStatus new ActivityStatus */ void setActivityStatus(ActivityStatus activityStatus) { // TODO: Mutex if (activityStatus == this.activityStatus) return; // No op // No point in going backwards if (activityStatus == ActivityStatus.UNREAD && this.activityStatus == ActivityStatus.HIGHLIGHT) return; this.activityStatus = activityStatus; if (logger.isLoggable(Level.FINE)) logger.fine("Activity status of " + this + " is now " + activityStatus); // TODO: This is fking ugly and a probable source of erroneous behavior. There's no guarantee that this method // is always called after a new message has been added. Message latest = messages.isEmpty() ? null : messages.last(); for (ActivityStatusListener activityStatusListener : session.getActivityStatusListeners()) { switch (activityStatus) { case NONE: activityStatusListener.onNone(this); break; case UNREAD: activityStatusListener.onUnread(this, latest); break; case HIGHLIGHT: activityStatusListener.onHighlight(this, latest); break; } } } abstract public String getName(); public void loadHistory(AckListener ackListener) { LoadHistory a = new LoadHistory(); // Ugly reference to lower level if (this instanceof Channel) { a.setChannelId(id); } else if (this instanceof Dialogue) { a.setUserId(id); } else { throw new UnsupportedOperationException(); } a.setHistoryLength(DEFAULT_HISTORY_SIZE); // TODO: Configurable if (!messages.isEmpty()) { a.setMessageId(messages.first().getId()); } a.setAckListener(ackListener); session.getTransport().enqueue(a); historyLoaded = true; } public String getId() { return id; } public void addConversationListener(ConversationListener conversationListener) { conversationListeners.add(conversationListener); } public void removeConversationListener(ConversationListener conversationListener) { conversationListeners.remove(conversationListener); } void unregisterSessionListener() { } public WrappedId getWrappedId() { return wrappedId; } public static abstract class WrappedId implements Serializable { protected final String id; public static final Pattern pattern = Pattern.compile("^/([pc])/([a-z0-9]+)$"); protected WrappedId(String id) { if (id == null) throw new IllegalArgumentException("Id can not be null!"); this.id = id; } public String getId() { return id; } public int hashCode() { return id.hashCode(); } public static WrappedId fromString(String s) { Matcher m = pattern.matcher(s); if (m.matches()) { if ("c".equals(m.group(1))) { return new Channel.WrappedId(m.group(2)); } else { assert "p".equals(m.group(1)); return new Dialogue.WrappedId(m.group(2)); } } else { throw new IllegalArgumentException("I don't understand: " + s); } } } public void sendMessage(MessagePayload payload) { sendMessage(payload, null); } /** * TODO: Exposing payload is probably too low level * TODO: Move to "ConversationUtils" or something * * @param payload */ public void sendMessage(MessagePayload payload, AckListener ackListener) { SendMessage a = new SendMessage(); // Ugly reference to lower level if (this instanceof Channel) { a.setChannelId(id); } else if (this instanceof Dialogue) { a.setUserId(id); } else { throw new UnsupportedOperationException(); } a.setMessageType(NinchatTextMessage.MESSAGE_TYPE); a.setPayloads(new MessagePayload[]{payload}); a.setAckListener(ackListener); session.getTransport().enqueue(a); } /** * Sends an action to server that removes us from the channel or dialogue. */ public abstract void leave(); public boolean isHistoryLoaded() { return historyLoaded; } private boolean containsHighlightTokens(Message message) { String text = message.getText(); Set<String> highlighTokens = session.getHighlightTokens(); if (text != null) { String[] tokens = text.split(HIGHLIGHT_TOKEN_SPLITTER); for (String token : tokens) { if (token.length() > 0 && highlighTokens.contains(token.toLowerCase())) { // TODO: Locale return true; } } } return false; } @Override public String toString() { return this.getClass().getSimpleName() + "/" + id + "/" + getName(); } }
package com.nomachetejuggling.ssl; import java.io.File; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.apache.commons.io.FileUtils; import org.joda.time.LocalDate; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.nomachetejuggling.ssl.model.Exercise; import com.nomachetejuggling.ssl.model.LogEntry; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.app.ActionBar; import android.app.Activity; import android.app.ProgressDialog; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.NumberPicker; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import android.support.v4.app.NavUtils; //TODO: UI fix //TODO: load previous logs from file //TODO: save current logs to file //TODO: prepopulate spinners to last value //TODO: handle pause/resume //TODO: undo button to undo previously logged entry public class LogActivity extends Activity { private List<LogEntry> currentLogs; private Exercise currentExercise; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log); // Show the Up button in the action bar. setupActionBar(); currentLogs = new ArrayList<LogEntry>(); } @Override protected void onStart() { super.onStart(); currentExercise = (Exercise)getIntent().getExtras().getSerializable("exercise"); Log.i("LogActivity", "Exercise: "+currentExercise.toString()); int numValues = 100; int PICKER_RANGE = 5; NumberPicker weightPicker = (NumberPicker) findViewById(R.id.weightPicker); String[] displayedValues = new String[numValues]; //Populate the array for(int i=0; i<numValues; i++) displayedValues[i] = String.valueOf(PICKER_RANGE * (i+1))+" lbs"; weightPicker.setMinValue(0); weightPicker.setMaxValue(displayedValues.length-1); weightPicker.setDisplayedValues(displayedValues); weightPicker.setWrapSelectorWheel(false); int maxReps=20; NumberPicker repsPicker = (NumberPicker) findViewById(R.id.repsPicker); String[] displayedReps = new String[maxReps]; //Populate the array for(int i=0; i<maxReps; i++) displayedReps[i] = (i+1)+" reps"; repsPicker.setMinValue(0); repsPicker.setMaxValue(displayedReps.length-1); repsPicker.setDisplayedValues(displayedReps); repsPicker.setWrapSelectorWheel(false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ActionBar ab = getActionBar(); ab.setTitle("Log"); ab.setSubtitle(currentExercise.getName()); } File dir = Util.getLogStorageDir(this.getApplicationContext()); File file = new File(dir, new LocalDate().toString("yyyy-MM-dd")+".json"); new PostTask(this).execute(file); } /** * Set up the {@link android.app.ActionBar}. */ private void setupActionBar() { getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. //getMenuInflater().inflate(R.menu.log, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // http://developer.android.com/design/patterns/navigation.html#up-vs-back NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } public void logSet(View view) { NumberPicker weightPicker = (NumberPicker) findViewById(R.id.weightPicker); NumberPicker repsPicker = (NumberPicker) findViewById(R.id.repsPicker); LogEntry log = new LogEntry(); log.exercise = currentExercise; log.weight = ((weightPicker.getValue()+1)*5); log.reps = (repsPicker.getValue()+1); this.currentLogs.add(log); this.persistCurrentLogs(); } public void loadCurrentLogs(List<LogEntry> readLogs) { currentLogs.clear(); currentLogs.addAll(readLogs); this.showCurrentLogs(); } public void persistCurrentLogs() { File dir = Util.getLogStorageDir(this.getApplicationContext()); File file = new File(dir, new LocalDate().toString("yyyy-MM-dd")+".json"); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(currentLogs); Log.d("IO", "Writing to " + file.getAbsolutePath() + "\n" + json); try { FileUtils.write(file, json, "UTF-8"); } catch(IOException e) { Toast.makeText( getApplicationContext(), getString(R.string.error_cannot_save_log), Toast.LENGTH_SHORT).show(); } showCurrentLogs(); } private void showCurrentLogs() { StringBuilder sb = new StringBuilder(); for(int i=0;i<this.currentLogs.size();i++) { LogEntry logEntry = this.currentLogs.get(i); if(logEntry.exercise.equals(currentExercise)) { sb.append(logEntry.toString()); //if(i!=this.currentLogs.size()-1) { sb.append("\n"); } } TextView currentLogs = (TextView)findViewById(R.id.currentLogsView); currentLogs.setText(sb); ScrollView scrollView = (ScrollView)findViewById(R.id.currentLogsScroll); scrollView.fullScroll(View.FOCUS_DOWN); } private static class PostTask extends AsyncTask<File, Void, List<LogEntry>> { private static ProgressDialog dialog; private LogActivity act; public PostTask(LogActivity act) { this.act = act; } @Override protected void onPreExecute() { super.onPreExecute(); dialog = ProgressDialog.show(act, "hrf", "brf"); } @Override protected List<LogEntry> doInBackground(File... params) { File file=params[0]; try { String json = FileUtils.readFileToString(file, "UTF-8"); Gson gson = new GsonBuilder().setPrettyPrinting().create(); Log.d("IO", "Start Reading from " + file.getAbsolutePath() + "\n" + json); Type collectionType = new TypeToken<Collection<LogEntry>>() {}.getType(); List<LogEntry> currentLogsRead = gson.fromJson(json, collectionType); return currentLogsRead; } catch (IOException e) { //Ignore, a missing file is either an unmounted SD Card (unrecoverable) or a first-time run. return new ArrayList<LogEntry>(); } } @Override protected void onPostExecute(List<LogEntry> result) { super.onPostExecute(result); act.loadCurrentLogs(result); dialog.hide(); } } }
package com.opencms.flex.util; import java.util.*; /** * The idea of this cache is, to separate the caching policy from the data structure * where the cached objects are stored. The advantage of doing so is, that the CmsFlexLruCache * can identify the last-recently-used object in O(1), whereas you would need at least * O(n) to traverse the data structure that stores the cached objects. Second, you can * easily use the CmsFlexLruCache to get an LRU cache, no matter what data structure is used to * store your objects. * <p> * The cache policy is affected by the "costs" of the objects being cached. Valuable cache costs * might be the byte size of the cached objects for example. * <p> * To add/remove cached objects from the data structure that stores them, the objects have to * implement the methods defined in the interface I_CmsFlexLruCacheObject to be notified when they * are added/removed from the CmsFlexLruCache. * * @see com.opencms.flex.util.I_CmsFlexLruCacheObject * @author Thomas Weckert (t.weckert@alkacon.com) * @version $Revision: 1.3 $ */ public class CmsFlexLruCache extends java.lang.Object { /** The head of the list of double linked LRU cache objects. */ private I_CmsFlexLruCacheObject m_ListHead; /** The tail of the list of double linked LRU cache objects. */ private I_CmsFlexLruCacheObject m_ListTail; /** Force a finalization after down-sizing the cache? */ private boolean m_ForceFinalization; /** The max. sum of costs the cached objects might reach. */ private int m_MaxCacheCosts; /** The avg. sum of costs the cached objects. */ private int m_AvgCacheCosts; /** The max. costs of cacheable objects. */ private int m_MaxObjectCosts; /** The costs of all cached objects. */ private int m_ObjectCosts; /** The sum of all cached objects. */ private int m_ObjectCount; /** Internal debug switch */ private static final int DEBUG = 0; /** * The constructor with all options. * * @param theMaxCacheCosts the max. cache costs of all cached objects * @param theAvgCacheCosts the avg. cache costs of all cached objects * @param theMaxObjectCosts the max. allowed cache costs per object. Set theMaxObjectCosts to -1 if you don't want to limit the max. allowed cache costs per object * @param forceFinalization should be true if a system wide garbage collection/finalization is forced after objects were removed from the cache */ public CmsFlexLruCache( int theMaxCacheCosts, int theAvgCacheCosts, int theMaxObjectCosts, boolean forceFinalization ) { this.m_ForceFinalization = forceFinalization; this.m_MaxCacheCosts = theMaxCacheCosts; this.m_AvgCacheCosts = theAvgCacheCosts; this.m_MaxObjectCosts = theMaxObjectCosts; this.m_ObjectCosts = this.m_ObjectCount = 0; this.m_ListHead = this.m_ListTail = null; } /** * Constructor for a LRU cache with forced garbage collection/finalization. * * @param theMaxCacheCosts the max. cache costs of all cached objects * @param theAvgCacheCosts the avg. cache costs of all cached objects * @param theMaxObjectCosts the max. allowed cache costs per object. Set theMaxObjectCosts to -1 if you don't want to limit the max. allowed cache costs per object */ public CmsFlexLruCache( int theMaxCacheCosts, int theAvgCacheCosts, int theMaxObjectCosts ) { this( theMaxCacheCosts, theAvgCacheCosts, theMaxObjectCosts, false ); } /** * Constructor for a LRU cache with forced garbage collection/finalization, the max. allowed costs of cacheable * objects is 1/4 of the max. costs of all cached objects. * * @param theMaxCacheCosts the max. cache costs of all cached objects * @param theAvgCacheCosts the avg. cache costs of all cached objects */ public CmsFlexLruCache( int theMaxCacheCosts, int theAvgCacheCosts ) { this( theMaxCacheCosts, theAvgCacheCosts, theMaxCacheCosts/4, false ); } /** * Constructor for a LRU cache where the max. allowed costs of cacheable objects is 1/4 of the max. costs of all cached objects. * * @param theMaxCacheCosts the max. cache costs of all cached objects * @param theAvgCacheCosts the avg. cache costs of all cached objects * @param forceFinalization should be true if a system wide garbage collection/finalization is forced after objects were removed from the cache */ public CmsFlexLruCache( int theMaxCacheCosts, int theAvgCacheCosts, boolean forceFinalization ) { this( theMaxCacheCosts, theAvgCacheCosts, theMaxCacheCosts/4, forceFinalization ); } /** * Returns a string representing the current state of the cache. */ public String toString() { String objectInfo = "\n"; objectInfo += "max. cache costs of all cached objects: " + this.m_MaxCacheCosts + "\n"; objectInfo += "avg. cache costs of all cached objects: " + this.m_AvgCacheCosts + "\n"; objectInfo += "max. cache costs per object: " + this.m_MaxObjectCosts + "\n"; objectInfo += "costs of all cached objects: " + this.m_ObjectCosts + "\n"; objectInfo += "sum of all cached objects: " + this.m_ObjectCount + "\n"; if (!this.m_ForceFinalization) { objectInfo += "no "; } objectInfo += "system garbage collection is forced during clean up\n"; return objectInfo; } /** * Add a new object to the cache. If you try to add the same object more than once, * the object is touched instead. * * @param theCacheObject the object being added to the cache * @return true if the object was added to the cache, false if the object was denied because its cache costs were higher than the allowed max. cache costs per object */ public synchronized boolean add( I_CmsFlexLruCacheObject theCacheObject ) { boolean retVal = false; if (theCacheObject==null) { // null can't be added or touched in the cache return false; } // only objects with cache costs < the max. allowed object cache costs can be cached! if ( (this.m_MaxObjectCosts!=-1) && (theCacheObject.getLruCacheCosts()>this.m_MaxObjectCosts) ) { this.log( "you are trying to cache objects with cache costs " + theCacheObject.getLruCacheCosts() + " which is bigger than the max. allowed costs " + this.m_MaxObjectCosts ); return false; } if (!this.isCached(theCacheObject)) { // add the object to the list of all cached objects in the cache this.addHead( theCacheObject ); } else { this.touch( theCacheObject ); } // check if the cache has to trash the last-recently-used objects before adding a new object if (this.m_ObjectCosts>this.m_MaxCacheCosts) { this.gc(); } return true; } /** * Test if a given object resides inside the cache. * @return true if the object is inside the cache, false otherwise */ private boolean isCached( I_CmsFlexLruCacheObject theCacheObject ) { if (theCacheObject==null || this.m_ObjectCount==0) { // the cache is empty or the object is null (which is never cached) return false; } if (theCacheObject.getNextLruObject()!=null || theCacheObject.getPreviousLruObject()!=null) { // the object has either a predecessor or successor in the linked // list of all cached objects, so it is inside the cache return true; } if (theCacheObject.getNextLruObject()==null && theCacheObject.getPreviousLruObject()==null) { if (this.m_ObjectCount==1 && this.m_ListHead.equals(theCacheObject) && this.m_ListTail.equals(theCacheObject)) { // the object is the one and only object in the cache return true; } } return false; } /** * Touch an existing object in the cache in the sense that it's "last-recently-used" state * is updated. * * @param theCacheObject the object being touched */ public synchronized boolean touch( I_CmsFlexLruCacheObject theCacheObject ) { if (!this.isCached(theCacheObject)) return false; // only objects with cache costs < the max. allowed object cache costs can be cached! if ( (this.m_MaxObjectCosts!=-1) && (theCacheObject.getLruCacheCosts()>this.m_MaxObjectCosts) ) { this.log( "you are trying to cache objects with cache costs " + theCacheObject.getLruCacheCosts() + " which is bigger than the max. allowed costs " + this.m_MaxObjectCosts ); this.remove( theCacheObject ); return false; } // set the list pointers correct if (theCacheObject.getNextLruObject()==null) { // case 1: the object is already at the head pos. return true; } else if (theCacheObject.getPreviousLruObject()==null) { // case 2: the object at the tail pos., remove it from the tail to put it to the front as the new head I_CmsFlexLruCacheObject newTail = theCacheObject.getNextLruObject(); newTail.setPreviousLruObject( null ); this.m_ListTail = newTail; } else { // case 3: the object is somewhere within the list, remove it to put it the front as the new head theCacheObject.getPreviousLruObject().setNextLruObject( theCacheObject.getNextLruObject() ); theCacheObject.getNextLruObject().setPreviousLruObject( theCacheObject.getPreviousLruObject() ); } // set the touched object as the new head in the linked list: I_CmsFlexLruCacheObject oldHead = this.m_ListHead; oldHead.setNextLruObject( theCacheObject ); theCacheObject.setNextLruObject( null ); theCacheObject.setPreviousLruObject( oldHead ); this.m_ListHead = theCacheObject; return true; } /** * Adds a cache object as the new haed to the list of all cached objects. * * @param theCacheObject the object being added as the new head to the list of all cached objects */ private void addHead( I_CmsFlexLruCacheObject theCacheObject ) { // set the list pointers correct if (this.m_ObjectCount>0) { // there is at least 1 object already in the list I_CmsFlexLruCacheObject oldHead = this.m_ListHead; oldHead.setNextLruObject( theCacheObject ); theCacheObject.setPreviousLruObject( oldHead ); this.m_ListHead = theCacheObject; } else { // it is the first object to be added to the list this.m_ListTail = this.m_ListHead = theCacheObject; theCacheObject.setPreviousLruObject( null ); } theCacheObject.setNextLruObject( null ); // update cache stats. and notify the cached object this.increaseCache( theCacheObject ); } /** * Removes an object from the list of all cached objects, * no matter what position it has inside the list. * * @param theCacheObject the object being removed from the list of all cached objects * @return a reference to the object that was removed */ public synchronized I_CmsFlexLruCacheObject remove( I_CmsFlexLruCacheObject theCacheObject ) { if (!this.isCached(theCacheObject)) { // this object was never ever before added to the cache return null; } // set the list pointers correct if (theCacheObject.getNextLruObject()==null) { // remove the object from the head pos. I_CmsFlexLruCacheObject newHead = theCacheObject.getPreviousLruObject(); newHead.setNextLruObject( null ); this.m_ListHead = newHead; } else if (theCacheObject.getPreviousLruObject()==null) { // remove the object from the tail pos. I_CmsFlexLruCacheObject newTail = theCacheObject.getNextLruObject(); newTail.setPreviousLruObject( null ); this.m_ListTail = newTail; } else { // remove the object from within the list theCacheObject.getPreviousLruObject().setNextLruObject( theCacheObject.getNextLruObject() ); theCacheObject.getNextLruObject().setPreviousLruObject( theCacheObject.getPreviousLruObject() ); } // update cache stats. and notify the cached object this.decreaseCache( theCacheObject ); return theCacheObject; } /** * Removes the tailing object from the list of all cached objects. */ private synchronized void removeTail() { I_CmsFlexLruCacheObject oldTail = null; if ((oldTail=this.m_ListTail)!=null) { I_CmsFlexLruCacheObject newTail = oldTail.getNextLruObject(); // set the list pointers correct if (newTail!=null) { // there are still objects remaining in the list newTail.setPreviousLruObject( null ); this.m_ListTail = newTail; } else { // we removed the last object from the list this.m_ListTail = this.m_ListHead = null; } // update cache stats. and notify the cached object this.decreaseCache( oldTail ); } } /** * Decrease the cache stats. and notify the cached object that it was removed from the cache. * * @param theCacheObject the object being notified that it was removed from the cache */ private void decreaseCache( I_CmsFlexLruCacheObject theCacheObject ) { // notify the object that it was now removed from the cache //theCacheObject.notify(); theCacheObject.removeFromLruCache(); // set the list pointers to null theCacheObject.setNextLruObject( null ); theCacheObject.setPreviousLruObject( null ); // update the cache stats. this.m_ObjectCosts -= theCacheObject.getLruCacheCosts(); this.m_ObjectCount } /** * Increase the cache stats. and notify the cached object that it was added to the cache. * * @param theCacheObject the object being notified that it was added to the cache */ private void increaseCache( I_CmsFlexLruCacheObject theCacheObject ) { // notify the object that it was now added to the cache //theCacheObject.notify(); theCacheObject.addToLruCache(); // update the cache stats. this.m_ObjectCosts += theCacheObject.getLruCacheCosts(); this.m_ObjectCount++; } /** * Removes the last recently used objects from the list of all cached objects as long * as the costs of all cached objects are higher than the allowed avg. costs of the cache. */ private void gc() { I_CmsFlexLruCacheObject currentObject = this.m_ListTail; while (currentObject!=null) { if (this.m_ObjectCosts<this.m_AvgCacheCosts) break; currentObject = currentObject.getNextLruObject(); this.removeTail(); } if (m_ForceFinalization) { // force a finalization/system garbage collection optionally Runtime.getRuntime().runFinalization(); System.gc(); } } /** * Write a message to the log media. * * @param theLogMessage the message being logged */ private void log( String theLogMessage ) { if (com.opencms.core.A_OpenCms.isLogging() && com.opencms.boot.I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING) { com.opencms.boot.CmsBase.log(com.opencms.boot.CmsBase.C_FLEX_CACHE, "[" + this.getClass().getName() + "] " + theLogMessage ); } } /** * Returns the count of all cached objects. * * @return the count of all cached objects */ public int size() { return this.m_ObjectCount; } /** * Clears the cache for finalization. */ protected void finalize() throws java.lang.Throwable { this.clear(); super.finalize(); } /** * Removes all cached objects and resets the internal cache. */ public void clear() { // remove all objects from the linked list from the tail to the head: I_CmsFlexLruCacheObject currentObject = this.m_ListTail; while (currentObject!=null) { currentObject = currentObject.getNextLruObject(); this.removeTail(); } this.m_ObjectCosts = this.m_ObjectCount = 0; this.m_ListHead = this.m_ListTail = null; if (m_ForceFinalization) { // force a finalization/system garbage collection optionally Runtime.getRuntime().runFinalization(); System.gc(); } } /** * Returns the avg. costs of all cached objects. * @return the avg. costs of all cached objects */ public int getAvgCacheCosts() { return this.m_AvgCacheCosts; } /** * Returns the max. costs of all cached objects. * @return the max. costs of all cached objects */ public int getMaxCacheCosts() { return this.m_MaxCacheCosts; } /** * Returns the max. allowed costs per cached object. * @return the max. allowed costs per cached object */ public int getMaxObjectCosts() { return this.m_MaxObjectCosts; } /** * Returns the cur. costs of all cached objects. * @return the cur. costs of all cached objects */ public int getObjectCosts() { return this.m_ObjectCosts; } }
package com.inmobi.messaging.netty; import java.net.InetSocketAddress; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.util.HashedWheelTimer; import org.jboss.netty.util.Timer; import scribe.thrift.ResultCode; import com.inmobi.instrumentation.TimingAccumulator; import com.inmobi.instrumentation.TimingAccumulator.Outcome; import com.inmobi.messaging.Message; public class ScribeTopicPublisher { private static final Log LOG = LogFactory.getLog(ScribeTopicPublisher.class); private final Timer timer = new HashedWheelTimer(); private ClientBootstrap bootstrap; private volatile Channel thisChannel = null; private String topic; private String host; private int port; private TimingAccumulator stats; private BlockingQueue<Message> toBeSent; private BlockingQueue<Message> toBeAcked; private long sleepInterval = 10; private boolean stopped = false; private Thread senderThread; private ScribeHandler handler; private boolean resendOnAckLost = false; private boolean reconnectionInProgress = false; private boolean enabledRetries = true; private int numDrainsOnClose = 10; /** * This is meant to be a way for async callbacks to set the channel on a * successful connection * * Java does not have pointers to pointers. So have to resort to sending in a * wrapper object that knows to update our pointer */ class ChannelSetter { public Channel getCurrentChannel() { return ScribeTopicPublisher.this.thisChannel; } public void setChannel(Channel ch) { Channel oldChannel = ScribeTopicPublisher.this.thisChannel; if (ch != oldChannel) { LOG.info("setting channel to " + ch.getId()); ScribeTopicPublisher.this.thisChannel = ch; if (oldChannel != null && oldChannel.isOpen()) { LOG.info("Closing old channel " + oldChannel.getId()); oldChannel.close().awaitUninterruptibly(); } } } public Channel connect() throws Exception { Channel channel = null; try { LOG.info("Connecting to scribe host:" + host + " port:" + port); ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); channel = future.awaitUninterruptibly().getChannel(); if (!future.isSuccess()) { LOG.info("Could not connect to Scribe"); if (future.getCause() instanceof Throwable) { throw new RuntimeException(future.getCause()); } else { throw (Exception)future.getCause(); } } else { LOG.info("Connected to Scribe"); setChannel(channel); return channel; } } catch (Exception e) { throw e; } } } public void init(String topic, String host, int port, int backoffSeconds, int timeoutSeconds, TimingAccumulator stats, boolean enableRetries, boolean resendOnAckLost, long sleepInterval, int msgQueueSize, int ackQueueSize, int numDrainsOnClose) { this.topic = topic; this.stats = stats; this.host = host; this.port = port; this.enabledRetries = enableRetries; this.resendOnAckLost = resendOnAckLost; this.sleepInterval = sleepInterval; this.toBeSent = new LinkedBlockingQueue<Message>(msgQueueSize); this.toBeAcked = new LinkedBlockingQueue<Message>(ackQueueSize); this.numDrainsOnClose = numDrainsOnClose; bootstrap = new ClientBootstrap(NettyEventCore.getInstance().getFactory()); ChannelSetter chs = new ChannelSetter(); handler = new ScribeHandler(stats, chs, backoffSeconds, timer, this); ChannelPipelineFactory cfactory = new ScribePipelineFactory(handler, timeoutSeconds, timer); bootstrap.setPipelineFactory(cfactory); try { chs.connect(); } catch (Exception ioe) { LOG.info("Could not intialize the connection, scheduling reconnect"); handler.setInited(); handler.scheduleReconnect(); } handler.setInited(); senderThread = new Thread(new AsyncSender()); senderThread.start(); } protected void publish(Message m) { addToSend(m); trySending(); } private void addToSend(Message m) { synchronized (toBeSent) { if (toBeSent.remainingCapacity() == 0) { LOG.warn("Messages to be sent Queue is full," + " dropping the message"); stats.accumulateOutcomeWithDelta(Outcome.LOST, 0); return; } toBeSent.add(m); } } private boolean isSendQueueEmpty() { synchronized (toBeSent) { return toBeSent.isEmpty(); } } boolean isAckQueueEmpty() { synchronized (toBeAcked) { return toBeAcked.isEmpty(); } } void trySending() { if (isSendQueueEmpty()) { return; } if (isChannelConnected()) { if (isChannelWritable()) { synchronized (toBeSent) { while (toBeSent.peek() != null && send(toBeSent.peek())) { toBeSent.remove(); } } } } else { suggestReconnect(); } } private boolean send(Message m) { synchronized (toBeAcked) { if (toBeAcked.remainingCapacity() > 0) { toBeAcked.add(m.clone()); ScribeBites.publish(thisChannel, topic, m); return true; } else { LOG.info("Could not send earlier messages successfully, not" + " sending right now."); } } return false; } private class AsyncSender implements Runnable { @Override public void run() { while (!stopped && !Thread.interrupted()) { trySending(); try { Thread.sleep(sleepInterval); } catch (InterruptedException ie) { LOG.info("Async sender interrupted. Exiting"); } } } } private boolean isChannelConnected() { if (thisChannel == null) { LOG.info("Channel is not initialized yet, not sending right now"); return false; } if (!thisChannel.isConnected()) { LOG.info("Channel is not connected, not sending right now"); return false; } return true; } private boolean isChannelWritable() { if (reconnectionInProgress) { LOG.info("Reconnection in progress, not sending right now"); return false; } if (!thisChannel.isWritable()) { LOG.info("Channel is not writable, not sending right now"); return false; } return true; } private void suggestReconnect() { handler.scheduleReconnect(); } private void drainAll() { LOG.info("Draining all the messages"); int numRetries = 0; while (true) { trySending(); if (isSendQueueEmpty() && isAckQueueEmpty()) { break; } if ((numDrainsOnClose != -1 && numRetries > numDrainsOnClose)) { LOG.info("Dropping messages as channel is not connected or number of" + " retries exhausted"); emptyAckQueue(); emptyMsgQueue(); } numRetries++; try { Thread.sleep(sleepInterval); } catch (InterruptedException e) { LOG.info("Draining inturrupted. Exiting"); return; } } } void prepareReconnect() { reconnectionInProgress = true; emptyAckQueue(); } void doneReconnect() { reconnectionInProgress = false; } synchronized void emptyAckQueue() { if (resendOnAckLost) { synchronized (toBeSent) { synchronized (toBeAcked) { toBeSent.addAll(toBeAcked); toBeAcked.clear(); } } } else { synchronized (toBeAcked) { if (!toBeAcked.isEmpty()) { LOG.warn("Emptying ack queue of size:" + toBeAcked.size()); } while (!toBeAcked.isEmpty()) { toBeAcked.remove(); stats.accumulateOutcomeWithDelta(Outcome.GRACEFUL_FAILURE, 0); } } } } synchronized void emptyMsgQueue() { synchronized (toBeSent) { if (!toBeSent.isEmpty()) { LOG.warn("Emptying message queue of size:" + toBeSent.size()); } while (!toBeSent.isEmpty()) { toBeSent.remove(); stats.accumulateOutcomeWithDelta(Outcome.LOST, 0); } } } public void close() { stopped = true; if (senderThread != null) { senderThread.interrupt(); try { senderThread.join(); } catch (InterruptedException e) { LOG.info("join on sender Thread interrupted"); } } drainAll(); LOG.info("Closing the channel"); handler.prepareClose(); if (thisChannel != null) { thisChannel.close().awaitUninterruptibly(); } timer.stop(); NettyEventCore.getInstance().releaseFactory(); } void ack(ResultCode success) { Message m; synchronized (toBeAcked) { if (!toBeAcked.isEmpty()) { m = toBeAcked.remove(); } else { LOG.info("Dropping the ack, as ack queue is empty"); return; } } if (success.getValue() == 0) { stats.accumulateOutcomeWithDelta(Outcome.SUCCESS, 0); } else { if (enabledRetries) { LOG.info("Could not send the message successfully, resending"); addToSend(m); stats.accumulateOutcomeWithDelta(Outcome.RETRY, 0); } else { LOG.warn("Could not send the message successfully. Got TRY_LATER"); stats.accumulateOutcomeWithDelta(Outcome.GRACEFUL_FAILURE, 0); } } } }
package com.sproutlife.renderer; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.Collection; import com.sproutlife.model.GameModel; import com.sproutlife.model.echosystem.Cell; import com.sproutlife.model.echosystem.Organism; import com.sproutlife.panel.GamePanel; public class BoardRenderer extends Renderer { private GamePanel gamePanel; private CellRenderer cellRenderer; private HeadRenderer headRenderer; private TailRenderer tailRenderer; private GenomeRenderer genomeRenderer; public BoardRenderer(GameModel gameModel, GamePanel gamePanel) { super(gameModel); this.gamePanel = gamePanel; this.cellRenderer = new CellRenderer(gameModel); this.headRenderer = new HeadRenderer(gameModel); this.tailRenderer = new TailRenderer(gameModel); this.genomeRenderer = new GenomeRenderer(gameModel); } private GamePanel getGamePanel() { return gamePanel; } public void paint(Graphics2D g) { /* AffineTransform t = new AffineTransform(); t.setToScale(2, 2); ((Graphics2D) g).setTransform(t); */ paintBackground(g); paintCells(g); paintOrgHeads(g); paintOrgTails(g); paintGenomes(g); } private void paintBackground(Graphics g) { g.setColor(new Color(248,248,248)); g.fillRect(0,0,getGamePanel().getWidth(),getGamePanel().getHeight()); } private void paintCells(Graphics2D g) { ArrayList<Cell> cells = getGameModel().getEchosystem().getCells(); for (Cell c : cells) { cellRenderer.paintCell(g, c); } } public void paintOrgHeads(Graphics2D g) { Collection<Organism> orgs = getGameModel().getEchosystem().getOrganisms(); for (Organism o : orgs) { headRenderer.paintHead(g, o); } } public void paintOrgTails(Graphics2D g) { Collection<Organism> orgs = getGameModel().getEchosystem().getOrganisms(); for (Organism o : orgs) { tailRenderer.paintTail(g, o); } } private void paintGenomes(Graphics2D g) { Collection<Organism> orgs = getGameModel().getEchosystem().getOrganisms(); for (Organism o : orgs) { genomeRenderer.paintGenome(g, o); } } }
package com.vmware.vim25.mo; import java.rmi.RemoteException; import com.vmware.vim25.*; /** * The managed object class corresponding to the one defined in VI SDK API reference. * @author Steve JIN (sjin@vmware.com), Lu Yu (lyu@vmware.com) */ public class HostNetworkSystem extends ExtensibleManagedObject { public HostNetworkSystem(ServerConnection serverConnection, ManagedObjectReference mor) { super(serverConnection, mor); } public HostNetCapabilities getCapabilities() { return (HostNetCapabilities) getCurrentProperty("capabilities"); } public HostIpRouteConfig getConsoleIpRouteConfig() { return (HostIpRouteConfig) getCurrentProperty("consoleIpRouteConfig"); } public HostDnsConfig getDnsConfig() { return (HostDnsConfig) getCurrentProperty("dnsConfig"); } public HostIpRouteConfig getIpRouteConfig() { return (HostIpRouteConfig) getCurrentProperty("ipRouteConfig"); } public HostNetworkConfig getNetworkConfig() { return (HostNetworkConfig) getCurrentProperty("networkConfig"); } public HostNetworkInfo getNetworkInfo() { return (HostNetworkInfo) getCurrentProperty("networkInfo"); } public HostNetOffloadCapabilities getOffloadCapabilities() { return (HostNetOffloadCapabilities) getCurrentProperty("offloadCapabilities"); } public void addPortGroup(HostPortGroupSpec portgrp) throws HostConfigFault, AlreadyExists, NotFound, RuntimeFault, RemoteException { getVimService().addPortGroup(getMOR(), portgrp); } public String addServiceConsoleVirtualNic(String portgroup, HostVirtualNicSpec spec) throws HostConfigFault, RuntimeFault, RemoteException { return getVimService().addServiceConsoleVirtualNic(getMOR(), portgroup, spec); } public String addVirtualNic(String portgroup, HostVirtualNicSpec nicSpec) throws HostConfigFault, AlreadyExists, RuntimeFault, RemoteException { return getVimService().addVirtualNic(getMOR(), portgroup, nicSpec); } public void addVirtualSwitch(String vswitchName, HostVirtualSwitchSpec spec) throws HostConfigFault, ResourceInUse, AlreadyExists, RuntimeFault, RemoteException { getVimService().addVirtualSwitch(getMOR(), vswitchName, spec); } public PhysicalNicHintInfo[] queryNetworkHint(String[] devices) throws HostConfigFault, NotFound, RuntimeFault, RemoteException { return getVimService().queryNetworkHint(getMOR(), devices); } public void refreshNetworkSystem() throws RuntimeFault, RemoteException { getVimService().refreshNetworkSystem(getMOR()); } public void removePortGroup(String pgName) throws HostConfigFault, ResourceInUse, NotFound, RuntimeFault, RemoteException { getVimService().removePortGroup(getMOR(), pgName); } public void removeServiceConsoleVirtualNic(String device) throws HostConfigFault, ResourceInUse, NotFound, RuntimeFault, RemoteException { getVimService().removeServiceConsoleVirtualNic(getMOR(), device); } public void removeVirtualNic(String device) throws HostConfigFault, NotFound, RuntimeFault, RemoteException { getVimService().removeVirtualNic(getMOR(), device); } public void removeVirtualSwitch(String vswitchName) throws HostConfigFault, ResourceInUse, NotFound, RuntimeFault, RemoteException { getVimService().removeVirtualSwitch(getMOR(), vswitchName); } public void restartServiceConsoleVirtualNic(String device) throws HostConfigFault, NotFound, RuntimeFault, RemoteException { getVimService().restartServiceConsoleVirtualNic(getMOR(), device); } public void updateConsoleIpRouteConfig(HostIpRouteConfig config) throws HostConfigFault, RuntimeFault, RemoteException { getVimService().updateConsoleIpRouteConfig(getMOR(), config); } public void updateDnsConfig(HostDnsConfig config) throws HostConfigFault, NotFound, RuntimeFault, RemoteException { getVimService().updateDnsConfig(getMOR(), config); } public void updateIpRouteConfig(HostIpRouteConfig config) throws HostConfigFault, RuntimeFault, RemoteException { getVimService().updateIpRouteConfig(getMOR(), config); } public void updateIpRouteTableConfig(HostIpRouteTableConfig config) throws HostConfigFault, RuntimeFault, RemoteException { getVimService().updateIpRouteTableConfig(getMOR(), config); } public void updateNetworkConfig(HostNetworkConfig config, String changeMode) throws HostConfigFault, AlreadyExists, NotFound, RuntimeFault, RemoteException { getVimService().updateNetworkConfig(getMOR(), config, changeMode); } public void updatePhysicalNicLinkSpeed(String device, PhysicalNicLinkInfo linkSpeed) throws HostConfigFault, NotFound, RuntimeFault, RemoteException { getVimService().updatePhysicalNicLinkSpeed(getMOR(), device, linkSpeed); } public void updatePortGroup(String pgName, HostPortGroupSpec portgrp) throws HostConfigFault, NotFound, RuntimeFault, RemoteException { getVimService().updatePortGroup(getMOR(), pgName, portgrp); } public void updateServiceConsoleVirtualNic(String device, HostVirtualNicSpec nic) throws HostConfigFault, ResourceInUse, NotFound, RuntimeFault, RemoteException { getVimService().updateServiceConsoleVirtualNic(getMOR(), device, nic); } public void updateVirtualNic(String device, HostVirtualNicSpec nic) throws HostConfigFault, NotFound, RuntimeFault, RemoteException { getVimService().updateVirtualNic(getMOR(), device, nic); } public void updateVirtualSwitch(String vswitchName, HostVirtualSwitchSpec spec) throws HostConfigFault, ResourceInUse, NotFound, RuntimeFault, RemoteException { getVimService().updateVirtualSwitch(getMOR(), vswitchName, spec); } }
package com.yc.pattern.iterator; /** * @author Yue Chang * @ClassName: MenuTestDrive * @Description: TODO * @date 2017/6/10 17:29 */ public class MenuTestDrive { public static void main(String[] args) { Menu pancakeHouseMenu = new PancakeHouseMenu(); Menu dinnerMenu = new DinnerMenu(); Menu cafeMenu = new CafeMenu(); Waitress waitress = new Waitress(pancakeHouseMenu,dinnerMenu,cafeMenu); waitress.printMenu(); /* // DinnerMenuIterator remove() Menu dinnerMenu = new DinnerMenu(); Iterator iterator = dinnerMenu.createIterator(); Waitress waitress = new Waitress(); // position //waitress.printMenu(iterator); //System.out.println(); iterator.next(); iterator.remove(); //waitress.printMenu(iterator); System.out.println(); */ } }
package dr.evomodel.tree; import dr.evolution.tree.Tree; import dr.evolution.tree.NodeRef; import dr.inference.model.*; import dr.xml.*; import java.util.*; import java.util.logging.Logger; /** * Two priors for the tree that are relatively non-informative on the internal node heights given the root height. * The first further assumes that the root height is truncated uniform, see Nicholls, G. & R.D. Gray (2004) for details. * The second allows any marginal specification over the root height given that it is larger than the oldest * sampling time (Bloomquist and Suchard, unpublished). * * @author Alexei Drummond * @author Andrew Rambaut * @author Erik Bloomquist * @author Marc Suchard * * @version $Id: UniformRootPrior.java,v 1.10 2005/05/24 20:25:58 rambaut Exp $ */ public class UniformRootPrior extends AbstractModelLikelihood { // PUBLIC STUFF public static final String UNIFORM_ROOT_PRIOR = "uniformRootPrior"; public static final String MAX_ROOT_HEIGHT = "maxRootHeight"; private static final double tolerance = 1E-6; private int k = 0; private double logFactorialK; private double maxRootHeight; private boolean isNicholls; Set<Double> tipDates = new TreeSet<Double>(); List<Double> reversedTipDateList = new ArrayList<Double>(); Map<Double, Integer> intervals = new TreeMap<Double, Integer>(); public UniformRootPrior(Tree tree) { this(UNIFORM_ROOT_PRIOR, tree); } private UniformRootPrior(String name, Tree tree) { super(name); this.tree = tree; this.isNicholls = false; if (tree instanceof TreeModel) { addModel((TreeModel) tree); } for (int i = 0; i < tree.getExternalNodeCount(); i++) { double h = tree.getNodeHeight(tree.getExternalNode(i)); tipDates.add(h); } if (tipDates.size() == 1) { // the tips are contemporaneous so these are constant... k = tree.getInternalNodeCount() - 1; Logger.getLogger("dr.evomodel").info("Uniform Root Prior, Intervals = " + (k + 1)); logFactorialK = logFactorial(k); } else { reversedTipDateList.addAll(tipDates); Collections.reverse(reversedTipDateList); // Prune out intervals smaller in length than tolerance double intervalStart = tree.getNodeHeight(tree.getRoot()); List<Double> pruneDates = new ArrayList<Double>(); for (Double intervalEnd : reversedTipDateList) { if (intervalStart - intervalEnd < tolerance) { pruneDates.add(intervalStart); } intervalStart = intervalEnd; } for (Double date : pruneDates) reversedTipDateList.remove(date); } } public UniformRootPrior(Tree tree, double maxRootHeight) { this(UNIFORM_ROOT_PRIOR, tree, maxRootHeight); } private UniformRootPrior(String name, Tree tree, double maxRootHeight) { super(name); this.tree = tree; this.maxRootHeight = maxRootHeight; isNicholls = true; if (tree instanceof TreeModel) { addModel((TreeModel) tree); } } UniformRootPrior(String name) { super(name); } // Extendable methods // ModelListener IMPLEMENTATION protected final void handleModelChangedEvent(Model model, Object object, int index) { likelihoodKnown = false; } // ParameterListener IMPLEMENTATION protected final void handleParameterChangedEvent(Parameter parameter, int index, Parameter.ChangeType type) { } // Model IMPLEMENTATION /** * Stores the precalculated state: in this case the intervals */ protected final void storeState() { storedLikelihoodKnown = likelihoodKnown; storedLogLikelihood = logLikelihood; } /** * Restores the precalculated state: that is the intervals of the tree. */ protected final void restoreState() { likelihoodKnown = storedLikelihoodKnown; logLikelihood = storedLogLikelihood; } protected final void acceptState() { } // nothing to do // Likelihood IMPLEMENTATION public final Model getModel() { return this; } public double getLogLikelihood() { return calculateLogLikelihood(); //if (!likelihoodKnown) { // logLikelihood = calculateLogLikelihood(); // likelihoodKnown = true; //return logLikelihood; } public final void makeDirty() { likelihoodKnown = false; } public double calculateLogLikelihood() { double rootHeight = tree.getNodeHeight(tree.getRoot()); if (isNicholls) { int nodeCount = tree.getExternalNodeCount(); if (rootHeight < 0 || rootHeight > (0.999 * maxRootHeight)) return Double.NEGATIVE_INFINITY; // from Nicholls, G. & R.D. Gray (2004) return rootHeight * (2 - nodeCount) - Math.log(maxRootHeight - rootHeight); } else { // the Bloomquist & Suchard variant // Let the sampling times and rootHeight specify the boundaries between a fixed number of intervals. // Internal node heights are equally likely to fall in any of these intervals and uniformly distributed // in an interval before sorting (i.e. the intercoalescent times in an interval form a scaled Dirchelet(1,1,\ldots,1) // This is a conditional density on the rootHeight, so it is possible to specify a marginal distribution // on the rootHeight given it is greater than the oldest sampling time. double logLike; if (k > 0) { // the tips are contemporaneous logLike = logFactorialK - (double) k * Math.log(rootHeight); } else { // int k1 = -1; // the root will always be > maxRootHeight // for (int i = 0; i < tree.getInternalNodeCount(); i++) { // double h = tree.getNodeHeight(tree.getInternalNode(i)); // if (h > maxTipHeight) { // logLike = logFactorial(k1) - (double) k1 * Math.log(rootHeight - maxTipHeight); // TODO Recalculate only when a tip sampling time changes if (!intervalCountsKnown) { intervals.clear(); for (Double date : reversedTipDateList) { intervals.put(date, 0); } traverse(tree, tree.getRoot()); intervalCountsKnown = true; } logLike = 0.0; for (Double date : reversedTipDateList) { double s = rootHeight - date; int k = intervals.get(date); // There was a bug here, was += if (k > 0) logLike += logFactorial(k) - (double) k * Math.log(s); } } assert !Double.isInfinite(logLike) && !Double.isNaN(logLike); return logLike; } } private double logFactorial(int n) { if (n == 0 || n == 1) { return 0; } double rValue = 0; for (int i = n; i > 1; i rValue += Math.log(i); } return rValue; } // private void addCountToInterval(double date) { // for(Double prunedDate : reversedTipDateList) { // if( date > prunedDate) { // intervals.put(prunedDate, intervals.get(prunedDate) + 1); // break; private Double traverse(Tree tree, NodeRef node) { Double date; if (tree.isExternal(node)) { date = tree.getNodeHeight(node); if (!intervals.keySet().contains(date)) { // Find closest within tolerance boolean found = false; for(Double prunedDate : reversedTipDateList) { if (Math.abs(date - prunedDate) < tolerance) { date = prunedDate; found = true; break; } } if (!found) throw new RuntimeException("Tip date not found"); } } else { Double date1 = traverse(tree, tree.getChild(node, 0)); Double date2 = traverse(tree, tree.getChild(node, 1)); date = (date1 > date2 ? date1 : date2); if (!tree.isRoot(node)) { // Only increases counts for internal nodes intervals.put(date, intervals.get(date) + 1); } } return date; } // XMLElement IMPLEMENTATION public org.w3c.dom.Element createElement(org.w3c.dom.Document d) { throw new RuntimeException("createElement not implemented"); } // Private and protected stuff public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return UNIFORM_ROOT_PRIOR; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); if (xo.hasAttribute(MAX_ROOT_HEIGHT)) { // the Nicholls & Gray variant double maxRootHeight = xo.getDoubleAttribute(MAX_ROOT_HEIGHT); return new UniformRootPrior(treeModel, maxRootHeight); } else { // the Bloomquist & Suchard variant return new UniformRootPrior(treeModel); } } /** * The tree. */ Tree tree = null; double logLikelihood; private double storedLogLikelihood; boolean likelihoodKnown = false; private boolean storedLikelihoodKnown = false; private boolean intervalCountsKnown = false; }
package dr.evomodel.tree; import dr.evolution.tree.Tree; import dr.evolution.tree.NodeRef; import dr.inference.model.*; import dr.xml.*; import java.util.*; import java.util.logging.Logger; /** * Two priors for the tree that are relatively non-informative on the internal node heights given the root height. * The first further assumes that the root height is truncated uniform, see Nicholls, G. & R.D. Gray (2004) for details. * The second allows any marginal specification over the root height given that it is larger than the oldest * sampling time (Bloomquist and Suchard, unpublished). * * @author Alexei Drummond * @author Andrew Rambaut * @author Erik Bloomquist * @author Marc Suchard * * @version $Id: UniformRootPrior.java,v 1.10 2005/05/24 20:25:58 rambaut Exp $ */ public class UniformRootPrior extends AbstractModelLikelihood { // PUBLIC STUFF public static final String UNIFORM_ROOT_PRIOR = "uniformRootPrior"; public static final String MAX_ROOT_HEIGHT = "maxRootHeight"; private static final double tolerance = 1E-6; private int k = 0; private double logFactorialK; private double maxRootHeight; private boolean isNicholls; Set<Double> tipDates = new TreeSet<Double>(); List<Double> reversedTipDateList = new ArrayList<Double>(); Map<Double, Integer> intervals = new TreeMap<Double, Integer>(); public UniformRootPrior(Tree tree) { this(UNIFORM_ROOT_PRIOR, tree); } private UniformRootPrior(String name, Tree tree) { super(name); this.tree = tree; this.isNicholls = false; if (tree instanceof TreeModel) { addModel((TreeModel) tree); } for (int i = 0; i < tree.getExternalNodeCount(); i++) { double h = tree.getNodeHeight(tree.getExternalNode(i)); tipDates.add(h); } if (tipDates.size() == 1) { // the tips are contemporaneous so these are constant... k = tree.getInternalNodeCount() - 1; Logger.getLogger("dr.evomodel").info("Uniform Root Prior, Intervals = " + (k + 1)); logFactorialK = logFactorial(k); } else { reversedTipDateList.addAll(tipDates); Collections.reverse(reversedTipDateList); // Prune out intervals smaller in length than tolerance double intervalStart = tree.getNodeHeight(tree.getRoot()); List<Double> pruneDates = new ArrayList<Double>(); for (Double intervalEnd : reversedTipDateList) { if (intervalStart - intervalEnd < tolerance) { pruneDates.add(intervalStart); } intervalStart = intervalEnd; } for (Double date : pruneDates) reversedTipDateList.remove(date); } } public UniformRootPrior(Tree tree, double maxRootHeight) { this(UNIFORM_ROOT_PRIOR, tree, maxRootHeight); } private UniformRootPrior(String name, Tree tree, double maxRootHeight) { super(name); this.tree = tree; this.maxRootHeight = maxRootHeight; isNicholls = true; if (tree instanceof TreeModel) { addModel((TreeModel) tree); } } UniformRootPrior(String name) { super(name); } // Extendable methods // ModelListener IMPLEMENTATION protected final void handleModelChangedEvent(Model model, Object object, int index) { likelihoodKnown = false; } // ParameterListener IMPLEMENTATION protected final void handleParameterChangedEvent(Parameter parameter, int index, Parameter.ChangeType type) { } // Model IMPLEMENTATION /** * Stores the precalculated state: in this case the intervals */ protected final void storeState() { storedLikelihoodKnown = likelihoodKnown; storedLogLikelihood = logLikelihood; } /** * Restores the precalculated state: that is the intervals of the tree. */ protected final void restoreState() { likelihoodKnown = storedLikelihoodKnown; logLikelihood = storedLogLikelihood; } protected final void acceptState() { } // nothing to do // Likelihood IMPLEMENTATION public final Model getModel() { return this; } public double getLogLikelihood() { return calculateLogLikelihood(); //if (!likelihoodKnown) { // logLikelihood = calculateLogLikelihood(); // likelihoodKnown = true; //return logLikelihood; } public final void makeDirty() { likelihoodKnown = false; } public double calculateLogLikelihood() { double rootHeight = tree.getNodeHeight(tree.getRoot()); if (isNicholls) { int nodeCount = tree.getExternalNodeCount(); if (rootHeight < 0 || rootHeight > (0.999 * maxRootHeight)) return Double.NEGATIVE_INFINITY; // from Nicholls, G. & R.D. Gray (2004) return rootHeight * (2 - nodeCount) - Math.log(maxRootHeight - rootHeight); } else { // the Bloomquist & Suchard variant // Let the sampling times and rootHeight specify the boundaries between a fixed number of intervals. // Internal node heights are equally likely to fall in any of these intervals and uniformly distributed // in an interval before sorting (i.e. the intercoalescent times in an interval form a scaled Dirchelet(1,1,\ldots,1) // This is a conditional density on the rootHeight, so it is possible to specify a marginal distribution // on the rootHeight given it is greater than the oldest sampling time. double logLike; if (k > 0) { // the tips are contemporaneous logLike = logFactorialK - (double) k * Math.log(rootHeight); } else { // // TODO Recalculate only when a tip sampling time changes // if (!intervalCountsKnown) { // intervals.clear(); // for (Double date : reversedTipDateList) { // intervals.put(date, 0); // traverse(tree, tree.getRoot()); // intervalCountsKnown = true; // logLike = 0.0; // for (Double date : reversedTipDateList) { // double s = rootHeight - date; // int k = intervals.get(date); // There was a bug here, was += // if (k > 0) // logLike += logFactorial(k) - (double) k * Math.log(s); tmpLogLikelihood = 0; recursivelyComputeConditionalUniform(tree, tree.getRoot(), 0.0); logLike = tmpLogLikelihood; } assert !Double.isInfinite(logLike) && !Double.isNaN(logLike); return logLike; } } private double recursivelyComputeConditionalUniform(Tree tree, NodeRef node, double parentHeight) { if(tree.isExternal(node)) return tree.getNodeHeight(node); double thisNodeHeight = tree.getNodeHeight(node); double childHeight1 = recursivelyComputeConditionalUniform(tree, tree.getChild(node,0), thisNodeHeight); double childHeight2 = recursivelyComputeConditionalUniform(tree, tree.getChild(node,1), thisNodeHeight); if (!tree.isRoot(node)) { double maxChildHeight = (childHeight1 > childHeight2 ? childHeight1 : childHeight2); tmpLogLikelihood -= Math.log(parentHeight - maxChildHeight); } return thisNodeHeight; } private double logFactorial(int n) { if (n == 0 || n == 1) { return 0; } double rValue = 0; for (int i = n; i > 1; i rValue += Math.log(i); } return rValue; } // private void addCountToInterval(double date) { // for(Double prunedDate : reversedTipDateList) { // if( date > prunedDate) { // intervals.put(prunedDate, intervals.get(prunedDate) + 1); // break; private Double traverse(Tree tree, NodeRef node) { Double date; if (tree.isExternal(node)) { date = tree.getNodeHeight(node); if (!intervals.keySet().contains(date)) { // Find closest within tolerance boolean found = false; for(Double prunedDate : reversedTipDateList) { if (Math.abs(date - prunedDate) < tolerance) { date = prunedDate; found = true; break; } } if (!found) throw new RuntimeException("Tip date not found"); } } else { Double date1 = traverse(tree, tree.getChild(node, 0)); Double date2 = traverse(tree, tree.getChild(node, 1)); date = (date1 > date2 ? date1 : date2); if (!tree.isRoot(node)) { // Only increases counts for internal nodes intervals.put(date, intervals.get(date) + 1); } } return date; } // XMLElement IMPLEMENTATION public org.w3c.dom.Element createElement(org.w3c.dom.Document d) { throw new RuntimeException("createElement not implemented"); } // Private and protected stuff public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return UNIFORM_ROOT_PRIOR; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); if (xo.hasAttribute(MAX_ROOT_HEIGHT)) { // the Nicholls & Gray variant double maxRootHeight = xo.getDoubleAttribute(MAX_ROOT_HEIGHT); return new UniformRootPrior(treeModel, maxRootHeight); } else { // the Bloomquist & Suchard variant return new UniformRootPrior(treeModel); } } /** * The tree. */ Tree tree = null; double logLikelihood; private double storedLogLikelihood; boolean likelihoodKnown = false; private boolean storedLikelihoodKnown = false; private boolean intervalCountsKnown = false; private double tmpLogLikelihood; }
package dr.inference.model; import dr.evomodel.continuous.SoftThresholdLikelihood; import dr.xml.*; import java.util.ArrayList; /** * A likelihood function which is simply the product of a set of likelihood functions. * * @author Andrew Rambaut * @author Alex Alekseyenko * @author Marc Suchard * @version $Id: CompoundLikelihood.java,v 1.19 2005/05/25 09:14:36 rambaut Exp $ */ public class PathLikelihood implements Likelihood { public static final String PATH_LIKELIHOOD = "pathLikelihood"; public static final String PATH_PARAMETER = "theta"; public static final String DIFFERENCE = "delta"; public static final String SOURCE = "source"; public static final String DESTINATION = "destination"; public static final String PSUEDO_SOURCE = "sourcePseudoPrior"; public static final String PSUEDO_DESTINATION = "destinationPseudoPrior"; public PathLikelihood(Likelihood source, Likelihood destination) { this(source, destination, null, null); } public PathLikelihood(Likelihood source, Likelihood destination, Likelihood pseudoSource, Likelihood pseudoDestination) { this.source = source; this.destination = destination; this.pseudoSource = pseudoSource; this.pseudoDestination = pseudoDestination; if(source!=null) { for (int j = 0; j < source.getModel().getModelCount(); j++) { for (int i = 0; i < source.getModel().getModel(j).getModelCount(); i++) { if (source.getModel().getModel(j).getModel(i) instanceof SoftThresholdLikelihood) { thresholdSofteners.add((SoftThresholdLikelihood) source.getModel().getModel(j).getModel(i)); } } } } if(pseudoSource!=null){ for (int i = 0; i < pseudoSource.getModel().getModelCount(); i++) { if(pseudoSource.getModel().getModel(i) instanceof SoftThresholdLikelihood){ thresholdSofteners.add((SoftThresholdLikelihood) pseudoSource.getModel().getModel(i)); } } } compoundModel.addModel(source.getModel()); compoundModel.addModel(destination.getModel()); } public double getPathParameter() { return pathParameter; } public void setPathParameter(double pathParameter) { this.pathParameter = pathParameter; if(thresholdSofteners!=null){ for(SoftThresholdLikelihood threshold:thresholdSofteners){ threshold.setPathParameter(pathParameter); } } } // Likelihood IMPLEMENTATION public Model getModel() { return compoundModel; } public double getLogLikelihood() { // Depends on complete model (include pseudo-densities) return (source.getLogLikelihood() * pathParameter) + (destination.getLogLikelihood() * (1.0 - pathParameter)); } public Likelihood getSourceLikelihood() { return source; } public Likelihood getDestinationLikelihood() { return destination; } public void makeDirty() { source.makeDirty(); destination.makeDirty(); } public boolean evaluateEarly() { return false; } public String toString() { return Double.toString(getLogLikelihood()); } // Loggable IMPLEMENTATION /** * @return the log columns. */ public dr.inference.loggers.LogColumn[] getColumns() { return new dr.inference.loggers.LogColumn[]{ new DeltaLogLikelihoodColumn(getId() + "." + DIFFERENCE), new PosteriorColumn(getId() + "." + SOURCE), new PriorColumn(getId() + "." + DESTINATION), new ThetaColumn(getId() + "." + PATH_PARAMETER), new PathLikelihoodColumn(getId() + "." + PATH_LIKELIHOOD) }; } private class PriorColumn extends dr.inference.loggers.NumberColumn { public PriorColumn(String label) { super(label); } public double getDoubleValue() { //assume that the prior is the destination in the BEAST xml return destination.getLogLikelihood(); } } private class PosteriorColumn extends dr.inference.loggers.NumberColumn { public PosteriorColumn(String label) { super(label); } public double getDoubleValue() { //assume that the posterior is the source in the BEAST xml return source.getLogLikelihood(); } } private class DeltaLogLikelihoodColumn extends dr.inference.loggers.NumberColumn { public DeltaLogLikelihoodColumn(String label) { super(label); } public double getDoubleValue() { // Remove pseudo-densities double sum=0; if(thresholdSofteners!=null){ for(SoftThresholdLikelihood threshold:thresholdSofteners){ sum+=threshold.getLikelihoodCorrection(); } } double logDensity = source.getLogLikelihood() - destination.getLogLikelihood()+sum; if (pseudoSource != null) { logDensity -= pseudoSource.getLogLikelihood(); } if (pseudoDestination != null) { // System.err.println("value = "+pseudoDestination.getLogLikelihood()); // logDensity += pseudoDestination.getLogLikelihood(); } return logDensity; } } private class ThetaColumn extends dr.inference.loggers.NumberColumn { public ThetaColumn(String label) { super(label); } public double getDoubleValue() { return pathParameter; } } private class PathLikelihoodColumn extends dr.inference.loggers.NumberColumn { public PathLikelihoodColumn(String label) { super(label); } public double getDoubleValue() { return getLogLikelihood(); } } public boolean isUsed() { return isUsed; } public void setUsed() { isUsed = true; } private boolean isUsed = false; // Identifiable IMPLEMENTATION private String id = null; public void setId(String id) { this.id = id; } public String getId() { return id; } public String prettyName() { return Abstract.getPrettyName(this); } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return PATH_LIKELIHOOD; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { Likelihood source = (Likelihood) xo.getElementFirstChild(SOURCE); Likelihood destination = (Likelihood) xo.getElementFirstChild(DESTINATION); Likelihood pseudoSource = null; if (xo.hasChildNamed(PSUEDO_SOURCE)) { pseudoSource = (Likelihood) xo.getElementFirstChild(PSUEDO_SOURCE); } Likelihood pseudoDestination = null; if (xo.hasChildNamed(PSUEDO_DESTINATION)) { pseudoDestination = (Likelihood) xo.getElementFirstChild(PSUEDO_DESTINATION); } return new PathLikelihood(source, destination, pseudoSource, pseudoDestination); }
package no.kantega.publishing.spring.scheduling; import no.kantega.publishing.api.configuration.SystemConfiguration; import no.kantega.publishing.api.runtime.ServerType; import no.kantega.publishing.api.scheduling.DisableOnServertype; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.scheduling.Trigger; import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler; import org.springframework.scheduling.support.ScheduledMethodRunnable; import javax.annotation.PostConstruct; import java.lang.reflect.Method; import java.util.Date; import java.util.concurrent.Delayed; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Custom TaskScheduler that extends the original by supporting annotations for * disabling certain jobs. * The {@code @DisableOnServertype annotation} can be used to say that the job annotated should not be run when the server * is running with a particular {@code ServerType} * * It is also possible to disable jobs with name.methodname.disable = true. e.g. * DatabaseCleanupJob.cleanDatabase.disable = true */ public class OpenAksessTaskScheduler extends ConcurrentTaskScheduler { private static final Logger log = LoggerFactory.getLogger(OpenAksessTaskScheduler.class); private final NoopScheduledFuture noopScheduledFuture = new NoopScheduledFuture(); @Autowired private ServerType serverType; @Autowired private SystemConfiguration configuration; @PostConstruct public void init() { setConcurrentExecutor(Executors.newFixedThreadPool(configuration.getInt("OpenAksessTaskScheduler.numThreads", 4))); } @Override public ScheduledFuture schedule(Runnable task, Trigger trigger) { return shouldScheduleTask(task) ? super.schedule(task, trigger): noopScheduledFuture; } @Override public ScheduledFuture schedule(Runnable task, Date startTime) { return shouldScheduleTask(task) ? super.schedule(task, startTime): noopScheduledFuture; } @Override public ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period) { return shouldScheduleTask(task) ? super.scheduleAtFixedRate(task, startTime, period): noopScheduledFuture; } @Override public ScheduledFuture scheduleAtFixedRate(Runnable task, long period) { return shouldScheduleTask(task) ? super.scheduleAtFixedRate(task, period): noopScheduledFuture; } @Override public ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay) { return shouldScheduleTask(task) ? super.scheduleWithFixedDelay(task, startTime, delay): noopScheduledFuture; } @Override public ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay) { return shouldScheduleTask(task) ? super.scheduleWithFixedDelay(task, delay): noopScheduledFuture; } @Override public void execute(Runnable task) { if (shouldScheduleTask(task)) { super.execute(task); } } @Override public void execute(Runnable task, long startTimeout) { if (shouldScheduleTask(task)) { super.execute(task, startTimeout); } } private boolean shouldScheduleTask(Runnable task) { boolean isDisabled = isDisabledByServertype(task) || isDisabledByConfig(task); return !isDisabled; } private boolean isDisabledByConfig(Runnable task) { if(task instanceof ScheduledMethodRunnable){ ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task; Method method = runnable.getMethod(); String configKey = method.getDeclaringClass().getSimpleName() + "." + method.getName() + ".disable"; return configuration.getBoolean(configKey, false); } return false; } private boolean isDisabledByServertype(Runnable task) { if(task instanceof ScheduledMethodRunnable){ ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task; Method method = runnable.getMethod(); DisableOnServertype annotation = AnnotationUtils.findAnnotation(method, DisableOnServertype.class); if(annotation != null){ ServerType disabledOnServertype = annotation.value(); return disabledOnServertype == serverType; } } return false; } @Override public Future<?> submit(Runnable task) { return shouldScheduleTask(task) ? super.submit(task): noopScheduledFuture; } private static class NoopScheduledFuture implements ScheduledFuture<Object> { @Override public long getDelay(TimeUnit unit) { log.debug("NoopScheduledFuture.getDelay({}) called", unit); return Long.MAX_VALUE; } @Override public int compareTo(Delayed o) { log.debug("NoopScheduledFuture.compareTo({}) called", o); return 1; } @Override public boolean cancel(boolean mayInterruptIfRunning) { log.debug("NoopScheduledFuture.cancel({}) called", mayInterruptIfRunning); return true; } @Override public boolean isCancelled() { log.debug("NoopScheduledFuture.isCancelled() called"); return false; } @Override public boolean isDone() { log.debug("NoopScheduledFuture.isDone() called"); return true; } @Override public Object get() throws InterruptedException, ExecutionException { log.debug("NoopScheduledFuture.get() called"); return null; } @Override public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { log.debug("NoopScheduledFuture.get({}, {}) called", timeout, unit); return null; } } }
package com.opengamma.strata.engine.calculations; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.opengamma.strata.collect.ArgChecker; /** * A wrapper around a {@link CalculationListener} that ensures the listener is only invoked by a single thread * at a time and calls {@link CalculationListener#calculationsComplete() calculationsComplete} when * all calculations have finished. */ public final class ListenerWrapper implements Consumer<CalculationResult> { private static final Logger log = LoggerFactory.getLogger(ListenerWrapper.class); /** The wrapped listener. */ private final CalculationListener listener; /** Queue of actions to perform on the delegate. */ private final Queue<CalculationResult> queue = new LinkedList<>(); /** Protects the queue and the executing flag. */ private final Lock lock = new ReentrantLock(); /** The total number of results expected. */ private final int expectedResultCount; /** * Flags whether a call to the underlying listener is executing. * If this flag is set when {@link #accept} is called, the result is added to * the queue and the calling thread returns. The executing thread will ensure * all queued results are delivered. */ private boolean executing; /** * Flags whether the calculations are complete. * This is set when the number of results received equals {@link #expectedResultCount}. * This causes a call to {@link CalculationListener#calculationsComplete()}. */ private boolean complete; /** The number of results received. */ private int resultCount; /** * @param listener the underlying listener wrapped by this object * @param expectedResultCount the number of results expected */ public ListenerWrapper(CalculationListener listener, int expectedResultCount) { this.listener = ArgChecker.notNull(listener, "listener"); this.expectedResultCount = ArgChecker.notNegativeOrZero(expectedResultCount, "expectedResultCount"); } /** * Accepts a calculation result and delivers it to the listener * <p> * This method can be invoked concurrently by multiple threads. * Only one of them will invoke the listener directly to ensure that * it is not accessed concurrently by multiple threads. * <p> * The other threads do not block while the listener is invoked. They * add their results to a queue and return quickly. Their results are * delivered by the thread invoking the listener. * * @param result the result of a calculation */ @Override public void accept(CalculationResult result) { // This is mutated while protected by the lock and accessed while not protected. // This is safe because the executing flag ensures the thread that accesses the // variable while unlocked is the same thread that set its value while guarded by the lock. CalculationResult nextResult; lock.lock(); try { if (executing) { // Another thread is already invoking the listener. Add the result to // the queue and return. The other thread will ensure the queued results // are delivered. queue.add(result); return; } else { // There is no thread invoking the listener. Set the executing flag to // ensure no other thread passes this point and invoke the listener. executing = true; nextResult = result; } } finally { lock.unlock(); } // Loop until the nextResult and all the results from the queue have been delivered for (;;) { try { // Invoke the listener while not protected by the lock. This allows other threads // to queue results while this thread is delivering them to the listener. listener.resultReceived(nextResult); } catch (RuntimeException e) { log.warn("Exception invoking listener.resultReceived", e); } lock.lock(); try { if (++resultCount == expectedResultCount) { // The expected number of results have been received. Set the complete // flag to trigger a call to listener.calculationsComplete after unlocking complete = true; break; } else if (queue.isEmpty()) { // There are no more results to deliver. Unset the executing flag and return. // This allows the next calling thread to deliver results. executing = false; break; } else { // There are results on the queue. This means another thread called accept(), // added a result to the queue and returned while this thread was invoking the listener. // This thread must deliver the results from the queue. nextResult = queue.remove(); } } finally { lock.unlock(); } } if (complete) { try { listener.calculationsComplete(); } catch (RuntimeException e) { log.warn("Exception invoking listener.calculationsComplete", e); } } } }
package edu.dynamic.dynamiz.parser; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.joestelmach.natty.DateGroup; import edu.dynamic.dynamiz.controller.Command; import edu.dynamic.dynamiz.controller.CommandType; import edu.dynamic.dynamiz.structure.MyDate; import edu.dynamic.dynamiz.structure.MyDateTime; /** * This is a Parser class that will parse the given input from the user into CommandLine object * which in turn into Command object of suitable type. It also provides the parsing of Date in explicit form * e.g. 13/12/2014 or implicit form, e.g. next Thurs. * * @author nhan * */ public class Parser { private static final String REGEX_DATE = "\\b(\\d{1,2})\\D*(\\d{1,2})\\D*(\\d{2}|\\d{4})\\b"; private static Parser parser = null; private final static Logger LoggerParser = Logger.getLogger(Parser.class.getName()); private Parser() { } public static Parser getInstance() { if (parser == null) { parser = new Parser(); } return parser; } /** * Retrieve a MyDate object of * * @param date * @return */ public MyDate parseDate(String dateStr) { assert dateStr != null; String dateStrUS = changeDateFormatUKToUS(dateStr); com.joestelmach.natty.Parser nattyParser = new com.joestelmach.natty.Parser(); List<DateGroup> groups = nattyParser.parse(dateStrUS); if (!groups.isEmpty()) { DateGroup group = groups.get(0); Date date = group.getDates().get(0); if (group.isTimeInferred()) { return new MyDate(date); } else { return new MyDateTime(date); } } else { LoggerParser.warning("Unrecognised date string: " + dateStr); return null; } } public List<String> parseDateList(List<String> unparsedList) { List<String> parsedList = new ArrayList<String>(); for (String dateStr: unparsedList) { MyDate date = parseDate(dateStr); if (date != null) { parsedList.add(date.toString()); } } return parsedList; } public List<String> parsePriorityList(List<String> unparsedList) { List<String> parsedList = new ArrayList<String>(); for (String priority: unparsedList) { // TODO: Implement checking of valid Priority String if (true) {//if (OptionType.PRIORITY.isValidString(priority)) { parsedList.add(priority); } } return parsedList; } public List<String> parseOrderingList(List<String> unparsedList) { List<String> parsedList = new ArrayList<String>(); for (String ordering: unparsedList) { OptionType type = OptionType.fromString(ordering); if (type != null) { parsedList.add(type.name()); } } return parsedList; } /** * Parse the input with the given regular expression based on the OptionType given. * The general format of the Pattern is as followed: * - Group 0: part to remove if there is a matching * - Group 1: matching keyword of OptionType * - Group 2: argument associating matching option type * * @param input The unparsed input * @param type OptionType to match the Option in return * @return an Option that is correctly parse or a null if there is no matching. */ public Option parseOptionAndExtract(StringBuffer input, OptionType type) { Option option = null; String regEx = type.getParsingRegex(); Pattern pattern = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(input.toString()); while (matcher.find()) { String argument = matcher.group(2); String[] values = argument.split("" + Option.DEFAULT_DELIMITER); // Sanitise values List<String> valueList = Util.removeEmptyStringsInArray(values); switch (type) { case START_TIME : // Fall through case END_TIME : // Fall through case ON_TIME : List<String> dateList = parseDateList(valueList); if (!dateList.isEmpty()) { option = new Option(type, dateList); input.replace(matcher.start(), matcher.end(), ""); } break; case PRIORITY : List<String> priorityList = parsePriorityList(valueList); if (!priorityList.isEmpty()) { option = new Option(type, priorityList); input.replace(matcher.start(), matcher.end(), ""); } break; case ORDER_BY : List<String> orderingList = parseOrderingList(valueList); if (!orderingList.isEmpty()) { option = new Option(type, orderingList); input.replace(matcher.start(), matcher.end(), ""); } break; default: throw new IllegalArgumentException("Invalid OptionType is given"); } } return option; } /** * Change date format from dd/mm/yy(yy) to mm/dd/yy(yy) format for natty parsing * * @param dateStr date string in format dd/mm/yy(yy) * @return date string in format mm/dd/yy(yy) */ public String changeDateFormatUKToUS(String dateStr) { assert(dateStr != null); return dateStr.replaceAll(REGEX_DATE, "$2/$1/$3"); } public Command parse(String inputCmd) { CommandLine cmdLine = parseCommandLine(inputCmd); return cmdLine.getCommand(); } public CommandLine parseCommandLine(String inputCmd) { assert(inputCmd != null); String commandWord = Util.getFirstWord(inputCmd); CommandType cmdType = CommandType.fromString(commandWord); inputCmd = Util.stripFirstWord(inputCmd); Options options = new Options(); StringBuffer inputCmdBuffer = new StringBuffer(inputCmd); for (OptionType optType: cmdType.getApplicableOptions()) { Option option = parseOptionAndExtract(inputCmdBuffer, optType); if (option != null) { options.add(option); } } String param = inputCmdBuffer.toString().trim(); CommandLine cmdLine = new CommandLine(cmdType, options, param); return cmdLine; } public static void main(String[] args) { Parser parser = Parser.getInstance(); } }
package org.honorato.multistatetogglebutton; import android.content.Context; import android.content.res.TypedArray; import android.os.Bundle; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import java.util.ArrayList; import java.util.List; public class MultiStateToggleButton extends ToggleButton { private static final String TAG = MultiStateToggleButton.class.getSimpleName(); private static final String KEY_BUTTON_STATES = "button_states"; private static final String KEY_INSTANCE_STATE = "instance_state"; List<View> buttons; boolean mMultipleChoice = false; private LinearLayout mainLayout; public MultiStateToggleButton(Context context) { super(context, null); if (this.isInEditMode()) { return; } } public MultiStateToggleButton(Context context, AttributeSet attrs) { super(context, attrs); if (this.isInEditMode()) { return; } int[] set = { android.R.attr.entries }; TypedArray a = context.obtainStyledAttributes(attrs, set); CharSequence[] texts = a.getTextArray(0); a.recycle(); setElements(texts, null, new boolean[texts.length]); } /** * If multiple choice is enabled, the user can select multiple * values simultaneously. * * @param enable */ public void enableMultipleChoice(boolean enable) { this.mMultipleChoice = enable; } @Override public Parcelable onSaveInstanceState() { Bundle bundle = new Bundle(); bundle.putParcelable(KEY_INSTANCE_STATE, super.onSaveInstanceState()); bundle.putBooleanArray(KEY_BUTTON_STATES, getStates()); return bundle; } @Override public void onRestoreInstanceState(Parcelable state) { if (state instanceof Bundle) { Bundle bundle = (Bundle) state; setStates(bundle.getBooleanArray(KEY_BUTTON_STATES)); state = bundle.getParcelable(KEY_INSTANCE_STATE); } super.onRestoreInstanceState(state); } /** * Set multiple buttons with the specified texts and default * initial values. Initial states are allowed, but both * arrays must be of the same size. * * @param texts An array of CharSequences for the buttons * @param imageResourceIds an optional icon to show, either text, icon or both needs to be set. * @param selected The default value for the buttons */ public void setElements(CharSequence[] texts, int[] imageResourceIds, boolean[] selected) { final int textCount = texts != null ? texts.length : 0; final int iconCount = imageResourceIds != null ? imageResourceIds.length : 0; final int elementCount = Math.max(textCount, iconCount); if (elementCount == 0) { throw new IllegalArgumentException("neither texts nor images are setup"); } boolean enableDefaultSelection = true; if (selected == null || elementCount != selected.length) { Log.d(TAG, "Invalid selection array"); enableDefaultSelection = false; } setOrientation(LinearLayout.HORIZONTAL); setGravity(Gravity.CENTER_VERTICAL); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (mainLayout == null) { mainLayout = (LinearLayout) inflater.inflate(R.layout.view_multi_state_toggle_button, this, true); } mainLayout.removeAllViews(); this.buttons = new ArrayList<>(); for (int i = 0; i < elementCount; i++) { Button b = null; if (i == 0) { // Add a special view when there's only one element if (elementCount == 1) { b = (Button) inflater.inflate(R.layout.view_single_toggle_button, mainLayout, false); } else { b = (Button) inflater.inflate(R.layout.view_left_toggle_button, mainLayout, false); } } else if (i == elementCount - 1) { b = (Button) inflater.inflate(R.layout.view_right_toggle_button, mainLayout, false); } else { b = (Button) inflater.inflate(R.layout.view_center_toggle_button, mainLayout, false); } b.setText(texts != null ? texts[i] : ""); if (imageResourceIds != null && imageResourceIds[i] != 0) { b.setCompoundDrawablesWithIntrinsicBounds(imageResourceIds[i], 0, 0, 0); } final int position = i; b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setValue(position); } }); mainLayout.addView(b); if (enableDefaultSelection) { setButtonState(b, selected[i]); } this.buttons.add(b); } mainLayout.setBackgroundResource(R.drawable.button_section_shape); } /** * Set multiple buttons with the specified texts and default * initial values. Initial states are allowed, but both * arrays must be of the same size. * * @param buttons the array of button views to use * @param selected The default value for the buttons */ public void setButtons(View[] buttons, boolean[] selected) { final int elementCount = buttons.length; if (elementCount == 0) { throw new IllegalArgumentException("neither texts nor images are setup"); } boolean enableDefaultSelection = true; if (selected == null || elementCount != selected.length) { Log.d(TAG, "Invalid selection array"); enableDefaultSelection = false; } setOrientation(LinearLayout.HORIZONTAL); setGravity(Gravity.CENTER_VERTICAL); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (mainLayout == null) { mainLayout = (LinearLayout) inflater.inflate(R.layout.view_multi_state_toggle_button, this, true); } mainLayout.removeAllViews(); this.buttons = new ArrayList<>(); for (int i = 0; i < elementCount; i++) { View b = buttons[i]; final int position = i; b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setValue(position); } }); mainLayout.addView(b); if (enableDefaultSelection) { setButtonState(b, selected[i]); } this.buttons.add(b); } mainLayout.setBackgroundResource(R.drawable.button_section_shape); } public void setElements(CharSequence[] elements) { int size = elements == null ? 0 : elements.length; setElements(elements, null, new boolean[size]); } public void setElements(List<?> elements) { int size = elements == null ? 0 : elements.size(); setElements(elements, new boolean[size]); } public void setElements(List<?> elements, Object selected) { int size = 0; int index = -1; if (elements != null) { size = elements.size(); index = elements.indexOf(selected); } boolean[] selectedArray = new boolean[size]; if (index != -1 && index < size) { selectedArray[index] = true; } setElements(elements, new boolean[size]); } public void setElements(List<?> texts, boolean[] selected) { int size = texts == null ? 0 : texts.size(); setElements(texts.toArray(new String[size]), null, selected); } public void setElements(int arrayResourceId, int selectedPosition) { // Get resources String[] elements = this.getResources().getStringArray(arrayResourceId); // Set selected boolean array int size = elements == null ? 0 : elements.length; boolean[] selected = new boolean[size]; if (selectedPosition >= 0 && selectedPosition < size) { selected[selectedPosition] = true; } // Super setElements(elements, null, selected); } public void setElements(int arrayResourceId, boolean[] selected) { setElements(this.getResources().getStringArray(arrayResourceId), null, selected); } public void setButtonState(View button, boolean selected) { if (button == null) { return; } button.setSelected(selected); // TODO: Inherit these colors from primary/secondary colors if (selected) { button.setBackgroundResource(R.drawable.button_pressed); } else { button.setBackgroundResource(R.drawable.button_not_pressed); } if (button instanceof Button) { ((Button) button).setTextAppearance(this.context, selected ? R.style.WhiteBoldText : R.style.PrimaryNormalText); } } public int getValue() { for (int i = 0; i < this.buttons.size(); i++) { if (buttons.get(i).isSelected()) { return i; } } return -1; } public void setValue(int position) { for (int i = 0; i < this.buttons.size(); i++) { if (mMultipleChoice) { if (i == position) { View b = buttons.get(i); if (b != null) { setButtonState(b, !b.isSelected()); } } } else { if (i == position) { setButtonState(buttons.get(i), true); } else if (!mMultipleChoice) { setButtonState(buttons.get(i), false); } } } super.setValue(position); } public boolean[] getStates() { int size = this.buttons == null ? 0 : this.buttons.size(); boolean[] result = new boolean[size]; for (int i = 0; i < size; i++) { result[i] = this.buttons.get(i).isSelected(); } return result; } public void setStates(boolean[] selected) { if (this.buttons == null || selected == null || this.buttons.size() != selected.length) { return; } int count = 0; for (View b : this.buttons) { setButtonState(b, selected[count]); count++; } } }
package com.yahoo.vespa.hosted.node.admin.component; import com.yahoo.vespa.athenz.api.AthenzService; import java.net.URI; import java.util.Collections; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; /** * Information necessary to e.g. establish communication with the config servers * * @author hakon */ public class ConfigServerInfo { private final List<String> configServerHostNames; private final URI loadBalancerEndpoint; private final AthenzService configServerIdentity; private final Function<String, URI> configServerHostnameToUriMapper; private final List<URI> configServerURIs; public ConfigServerInfo(String loadBalancerHostName, List<String> configServerHostNames, String scheme, int port, AthenzService configServerAthenzIdentity) { this.configServerHostNames = configServerHostNames; this.loadBalancerEndpoint = createLoadBalancerEndpoint(loadBalancerHostName, scheme, port); this.configServerIdentity = configServerAthenzIdentity; this.configServerHostnameToUriMapper = hostname -> URI.create(scheme + "://" + hostname + ":" + port); this.configServerURIs = configServerHostNames.stream() .map(configServerHostnameToUriMapper) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } private static URI createLoadBalancerEndpoint(String loadBalancerHost, String scheme, int port) { return URI.create(scheme + "://" + loadBalancerHost + ":" + port); } public List<String> getConfigServerHostNames() { return configServerHostNames; } public List<URI> getConfigServerUris() { return configServerURIs; } public URI getConfigServerUri(String hostname) { return configServerHostnameToUriMapper.apply(hostname); } public URI getLoadBalancerEndpoint() { return loadBalancerEndpoint; } public AthenzService getConfigServerIdentity() { return configServerIdentity; } }
package edu.wustl.xipHost.avt2ext; import java.io.File; import java.net.MalformedURLException; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.log4j.Logger; import org.nema.dicom.wg23.ArrayOfObjectDescriptor; import org.nema.dicom.wg23.ArrayOfPatient; import org.nema.dicom.wg23.ArrayOfSeries; import org.nema.dicom.wg23.ArrayOfStudy; import org.nema.dicom.wg23.AvailableData; import org.nema.dicom.wg23.Modality; import org.nema.dicom.wg23.ObjectDescriptor; import org.nema.dicom.wg23.ObjectLocator; import org.nema.dicom.wg23.Uid; import org.nema.dicom.wg23.Uuid; import edu.wustl.xipHost.avt2ext.iterator.IterationTarget; import edu.wustl.xipHost.avt2ext.iterator.SubElement; import edu.wustl.xipHost.avt2ext.iterator.TargetElement; import edu.wustl.xipHost.avt2ext.iterator.TargetIterator; import edu.wustl.xipHost.avt2ext.iterator.TargetIteratorListener; import edu.wustl.xipHost.dataModel.AIMItem; import edu.wustl.xipHost.dataModel.ImageItem; import edu.wustl.xipHost.dataModel.Item; import edu.wustl.xipHost.dataModel.Patient; import edu.wustl.xipHost.dataModel.SearchResult; import edu.wustl.xipHost.dataModel.Series; import edu.wustl.xipHost.dataModel.Study; import edu.wustl.xipHost.localFileSystem.WG23DataModelFileSystemImpl; import edu.wustl.xipHost.wg23.WG23DataModel; /** * @author Jaroslaw Krych * */ public class AVTUtil { final static Logger logger = Logger.getLogger(AVTUtil.class); //Object could be list of patients, studies or series public static SearchResult convertToSearchResult(Object object, SearchResult initialSearchResult, Object selectedObject){ SearchResult resultAD = null; if(initialSearchResult == null){ resultAD = new SearchResult("AD Database"); }else{ resultAD = initialSearchResult; } Patient patientFromAD = null; Study studyFromAD = null; Series seriesFromAD = null; Item itemFromAD = null; List<?> listOfObjects = (List<?>)object; Iterator<?> iter = listOfObjects.iterator(); while (iter.hasNext()) { java.lang.Object obj = iter.next(); if (obj == null) { System.out.println("something not right. obj is null"); continue; } SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy"); //selectedObject == null means it is a first query in a progressive query process if(selectedObject == null){ if(obj instanceof com.siemens.scr.avt.ad.dicom.Patient){ com.siemens.scr.avt.ad.dicom.Patient patientAD = com.siemens.scr.avt.ad.dicom.Patient.class.cast(obj); String patientName = patientAD.getPatientName(); if(patientName == null){patientName = "";} String patientID = patientAD.getPatientID(); if(patientID == null){patientID = "";} Date patientADBirthDate = patientAD.getPatientBirthDate(); Calendar patientBirthDate = Calendar.getInstance(); String strPatientBirthDate = null; if(patientADBirthDate != null){ patientBirthDate.setTime(patientADBirthDate); strPatientBirthDate = sdf.format(patientBirthDate.getTime()); if(strPatientBirthDate == null){strPatientBirthDate = "";} }else{ strPatientBirthDate = ""; } if(resultAD.contains(patientID) == false){ patientFromAD = new Patient(patientName, patientID, strPatientBirthDate); resultAD.addPatient(patientFromAD); } }else{ } } else if(selectedObject instanceof Patient){ patientFromAD = Patient.class.cast(selectedObject); com.siemens.scr.avt.ad.dicom.GeneralStudy studyAD = com.siemens.scr.avt.ad.dicom.GeneralStudy.class.cast(obj); Date studyDateTime = studyAD.getStudyDateTime(); Calendar calendar = Calendar.getInstance(); calendar.setTime(studyDateTime); String studyDate = null; if(calendar != null){ studyDate = sdf.format(calendar.getTime());if(studyDate == null){studyDate = "";} }else{ studyDate = ""; } String studyID = studyAD.getStudyID();if(studyID == null){studyID = "";} String studyDesc = studyAD.getStudyDescription();if(studyDesc == null){studyDesc = "";} String studyInstanceUID = studyAD.getStudyInstanceUID();if(studyInstanceUID == null){studyInstanceUID = "";} studyFromAD = new Study(studyDate, studyID, studyDesc, studyInstanceUID); if(patientFromAD.contains(studyInstanceUID) == false){ studyFromAD = new Study(studyDate, studyID, studyDesc, studyInstanceUID); patientFromAD.addStudy(studyFromAD); } Timestamp lastUpdated = new Timestamp(Calendar.getInstance().getTime().getTime()); patientFromAD.setLastUpdated(lastUpdated); } else if(selectedObject instanceof Study){ studyFromAD = Study.class.cast(selectedObject); com.siemens.scr.avt.ad.dicom.GeneralSeries seriesAD = com.siemens.scr.avt.ad.dicom.GeneralSeries.class.cast(obj); String seriesNumber = seriesAD.getSeriesNumber(); if(seriesNumber == null){seriesNumber = "";} String modality = seriesAD.getModality();if(modality == null){modality = "";} String seriesDesc = seriesAD.getSeriesDescription();if(seriesDesc == null){seriesDesc = "";} String seriesInstanceUID = seriesAD.getSeriesInstanceUID();if(seriesInstanceUID == null){seriesInstanceUID = "";} if(studyFromAD.contains(seriesInstanceUID) == false){ seriesFromAD = new Series(seriesNumber.toString(), modality, seriesDesc, seriesInstanceUID); studyFromAD.addSeries(seriesFromAD); } Timestamp lastUpdated = new Timestamp(Calendar.getInstance().getTime().getTime()); studyFromAD.setLastUpdated(lastUpdated); } else if(selectedObject instanceof Series){ seriesFromAD = Series.class.cast(selectedObject); if(obj instanceof com.siemens.scr.avt.ad.dicom.GeneralImage){ com.siemens.scr.avt.ad.dicom.GeneralImage itemAD = com.siemens.scr.avt.ad.dicom.GeneralImage.class.cast(obj); String itemSOPInstanceUID = itemAD.getSOPInstanceUID(); if(itemSOPInstanceUID == null){itemSOPInstanceUID = "";} if(seriesFromAD.containsItem(itemSOPInstanceUID) == false){ itemFromAD = new ImageItem(itemSOPInstanceUID); } }else if(obj instanceof String){ String imageAnnotationType = ""; String dateTime = ""; String authorName = ""; String aimUID = String.class.cast(obj); itemFromAD = new AIMItem(imageAnnotationType, dateTime, authorName, aimUID); } seriesFromAD.addItem(itemFromAD); Timestamp lastUpdated = new Timestamp(Calendar.getInstance().getTime().getTime()); seriesFromAD.setLastUpdated(lastUpdated); } } if(logger.isDebugEnabled()){ Iterator<Patient> patients = resultAD.getPatients().iterator(); while(patients.hasNext()){ Patient patient = patients.next(); Timestamp patientLastUpdated = patient.getLastUpdated(); String strPatientLastUpdated = null; if(patientLastUpdated != null){ strPatientLastUpdated = patientLastUpdated.toString(); } logger.debug(patient.toString() + " Last updated: " + strPatientLastUpdated); Iterator<Study> studies = patient.getStudies().iterator(); while(studies.hasNext()){ Study study = studies.next(); Timestamp studyLastUpdated = study.getLastUpdated(); String strStudyLastUpdated = null; if(studyLastUpdated != null){ strStudyLastUpdated = studyLastUpdated.toString(); } logger.debug(study.toString() + " Last updated: " + strStudyLastUpdated); Iterator<Series> series = study.getSeries().iterator(); while(series.hasNext()){ Series oneSeries = series.next(); Timestamp seriesLastUpdated = oneSeries.getLastUpdated(); String strSeriesLastUpdated = null; if(seriesLastUpdated != null){ strSeriesLastUpdated = seriesLastUpdated.toString(); } logger.debug(oneSeries.toString() + " Last updated: " + strSeriesLastUpdated); } } } } return resultAD; } public Iterator<TargetElement> createIterator(SearchResult selectedDataSearchResult, IterationTarget target, Query avtQuery, File pathTmpDir, TargetIteratorListener l){ TargetIterator targetIter = new TargetIterator(selectedDataSearchResult, target, avtQuery, pathTmpDir); targetIter.addTargetIteratorListener(l); Iterator<TargetElement> iter = targetIter; return iter; } @SuppressWarnings("unchecked") public synchronized WG23DataModel getWG23DataModel(TargetElement targetElement){ if(targetElement == null){return null;} AvailableData availableData = new AvailableData(); ArrayOfPatient arrayOfPatient = new ArrayOfPatient(); List<org.nema.dicom.wg23.Patient> listPatients = arrayOfPatient.getPatient(); org.nema.dicom.wg23.Patient patient = new org.nema.dicom.wg23.Patient(); List<SubElement> subElements = targetElement.getSubElements(); //patientName is the same for all subElements, therefore it is sufficient to get it for the first element at index 0. Map<Integer, Object> dicomCriteria = subElements.get(0).getCriteria().getDICOMCriteria(); String patientName = dicomCriteria.get(new Integer(1048592)).toString(); //patientName patient.setName(patientName); ArrayOfObjectDescriptor arrayOfObjectDescPatient = new ArrayOfObjectDescriptor(); patient.setObjectDescriptors(arrayOfObjectDescPatient); ArrayOfStudy arrayOfStudy = new ArrayOfStudy(); List<org.nema.dicom.wg23.Study> listOfStudies = arrayOfStudy.getStudy(); List<ObjectLocator> objLocators = new ArrayList<ObjectLocator>(); if(targetElement.getTarget().equals(IterationTarget.PATIENT)){ String currentStudyInstanceUID = null; ArrayOfSeries arrayOfSeries = null; for(SubElement subElement : subElements){ String studyInstanceUID = subElement.getCriteria().getDICOMCriteria().get(new Integer(2097165)).toString(); //studyInstanceUID String path = subElement.getPath(); IOFileFilter fileFilter = FileFilterUtils.trueFileFilter(); Iterator<File> files = FileUtils.iterateFiles(new File(path), fileFilter, null); if(currentStudyInstanceUID == null || !currentStudyInstanceUID.equalsIgnoreCase(studyInstanceUID)){ currentStudyInstanceUID = studyInstanceUID; org.nema.dicom.wg23.Study study = new org.nema.dicom.wg23.Study(); study.setStudyUID(studyInstanceUID); ArrayOfObjectDescriptor arrayOfObjectDescStudy = new ArrayOfObjectDescriptor(); study.setObjectDescriptors(arrayOfObjectDescStudy); arrayOfSeries = new ArrayOfSeries(); List<org.nema.dicom.wg23.Series> listOfSeries = arrayOfSeries.getSeries(); org.nema.dicom.wg23.Series series = new org.nema.dicom.wg23.Series(); String seriesInstanceUID = subElement.getCriteria().getDICOMCriteria().get(new Integer(2097166)).toString(); //seriesInstanceUID series.setSeriesUID(seriesInstanceUID); ArrayOfObjectDescriptor arrayOfObjectDesc = new ArrayOfObjectDescriptor(); List<ObjectDescriptor> listObjectDescs = arrayOfObjectDesc.getObjectDescriptor(); //create list of objDescs and add them to each series while(files.hasNext()){ File file = files.next(); ObjectDescriptor objDesc = new ObjectDescriptor(); Uuid objDescUUID = new Uuid(); objDescUUID.setUuid(UUID.randomUUID().toString()); objDesc.setUuid(objDescUUID); //check mime type String mimeType = null; objDesc.setMimeType(mimeType); Uid uid = new Uid(); String classUID = ""; uid.setUid(classUID); objDesc.setClassUID(uid); String modCode = ""; Modality modality = new Modality(); modality.setModality(modCode); objDesc.setModality(modality); listObjectDescs.add(objDesc); ObjectLocator objLoc = new ObjectLocator(); objLoc.setUuid(objDescUUID); try { objLoc.setUri(file.toURI().toURL().toExternalForm()); //getURI from the iterator } catch (MalformedURLException e) { logger.error(e, e); } objLocators.add(objLoc); } series.setObjectDescriptors(arrayOfObjectDesc); listOfSeries.add(series); study.setSeries(arrayOfSeries); listOfStudies.add(study); } else { List<org.nema.dicom.wg23.Series> listOfSeries = arrayOfSeries.getSeries(); org.nema.dicom.wg23.Series series = new org.nema.dicom.wg23.Series(); String seriesInstanceUID = subElement.getCriteria().getDICOMCriteria().get(new Integer(2097166)).toString(); //seriesInstanceUID series.setSeriesUID(seriesInstanceUID); ArrayOfObjectDescriptor arrayOfObjectDesc = new ArrayOfObjectDescriptor(); List<ObjectDescriptor> listObjectDescs = arrayOfObjectDesc.getObjectDescriptor(); //create list of objDescs and add them to each series while(files.hasNext()){ File file = files.next(); ObjectDescriptor objDesc = new ObjectDescriptor(); Uuid objDescUUID = new Uuid(); objDescUUID.setUuid(UUID.randomUUID().toString()); objDesc.setUuid(objDescUUID); //check mime type objDesc.setMimeType("application/dicom"); Uid uid = new Uid(); String classUID = ""; uid.setUid(classUID); objDesc.setClassUID(uid); String modCode = ""; Modality modality = new Modality(); modality.setModality(modCode); objDesc.setModality(modality); listObjectDescs.add(objDesc); ObjectLocator objLoc = new ObjectLocator(); objLoc.setUuid(objDescUUID); try { objLoc.setUri(file.toURI().toURL().toExternalForm()); //getURI from the iterator } catch (MalformedURLException e) { logger.error(e, e); } objLocators.add(objLoc); } series.setObjectDescriptors(arrayOfObjectDesc); listOfSeries.add(series); } } patient.setStudies(arrayOfStudy); listPatients.add(patient); availableData.setPatients(arrayOfPatient); ArrayOfObjectDescriptor arrayOfObjectDescTopLevel = new ArrayOfObjectDescriptor(); availableData.setObjectDescriptors(arrayOfObjectDescTopLevel); } else if(targetElement.getTarget().equals(IterationTarget.STUDY)) { String studyInstanceUID = subElements.get(0).getCriteria().getDICOMCriteria().get(new Integer(2097165)).toString(); //studyInstanceUID org.nema.dicom.wg23.Study study = new org.nema.dicom.wg23.Study(); study.setStudyUID(studyInstanceUID); ArrayOfObjectDescriptor arrayOfObjectDescStudy = new ArrayOfObjectDescriptor(); study.setObjectDescriptors(arrayOfObjectDescStudy); ArrayOfSeries arrayOfSeries = new ArrayOfSeries(); List<org.nema.dicom.wg23.Series> listOfSeries = arrayOfSeries.getSeries(); for(SubElement subElement : subElements){ String seriesInstanceUID = subElement.getCriteria().getDICOMCriteria().get(new Integer(2097166)).toString(); //seriesInstanceUID String path = subElement.getPath(); IOFileFilter fileFilter = FileFilterUtils.trueFileFilter(); Iterator<File> files = FileUtils.iterateFiles(new File(path), fileFilter, null); org.nema.dicom.wg23.Series series = new org.nema.dicom.wg23.Series(); series.setSeriesUID(seriesInstanceUID); ArrayOfObjectDescriptor arrayOfObjectDesc = new ArrayOfObjectDescriptor(); List<ObjectDescriptor> listObjectDescs = arrayOfObjectDesc.getObjectDescriptor(); //create list of objDescs and add them to each series while(files.hasNext()){ File file = files.next(); ObjectDescriptor objDesc = new ObjectDescriptor(); Uuid objDescUUID = new Uuid(); objDescUUID.setUuid(UUID.randomUUID().toString()); objDesc.setUuid(objDescUUID); //check mime type objDesc.setMimeType("application/dicom"); Uid uid = new Uid(); String classUID = ""; uid.setUid(classUID); objDesc.setClassUID(uid); String modCode = ""; Modality modality = new Modality(); modality.setModality(modCode); objDesc.setModality(modality); listObjectDescs.add(objDesc); ObjectLocator objLoc = new ObjectLocator(); objLoc.setUuid(objDescUUID); try { objLoc.setUri(file.toURI().toURL().toExternalForm()); //getURI from the iterator } catch (MalformedURLException e) { logger.error(e, e); } objLocators.add(objLoc); } series.setObjectDescriptors(arrayOfObjectDesc); listOfSeries.add(series); } study.setSeries(arrayOfSeries); listOfStudies.add(study); patient.setStudies(arrayOfStudy); listPatients.add(patient); availableData.setPatients(arrayOfPatient); ArrayOfObjectDescriptor arrayOfObjectDescTopLevel = new ArrayOfObjectDescriptor(); availableData.setObjectDescriptors(arrayOfObjectDescTopLevel); } else if(targetElement.getTarget().equals(IterationTarget.SERIES)) { String studyInstanceUID = subElements.get(0).getCriteria().getDICOMCriteria().get(new Integer(2097165)).toString(); //studyInstanceUID String path = subElements.get(0).getPath(); IOFileFilter fileFilter = FileFilterUtils.trueFileFilter(); Iterator<File> files = FileUtils.iterateFiles(new File(path), fileFilter, null); org.nema.dicom.wg23.Study study = new org.nema.dicom.wg23.Study(); study.setStudyUID(studyInstanceUID); ArrayOfObjectDescriptor arrayOfObjectDescStudy = new ArrayOfObjectDescriptor(); study.setObjectDescriptors(arrayOfObjectDescStudy); ArrayOfSeries arrayOfSeries = new ArrayOfSeries(); List<org.nema.dicom.wg23.Series> listOfSeries = arrayOfSeries.getSeries(); org.nema.dicom.wg23.Series series = new org.nema.dicom.wg23.Series(); String seriesInstanceUID = subElements.get(0).getCriteria().getDICOMCriteria().get(new Integer(2097166)).toString(); //seriesInstanceUID series.setSeriesUID(seriesInstanceUID); ArrayOfObjectDescriptor arrayOfObjectDesc = new ArrayOfObjectDescriptor(); List<ObjectDescriptor> listObjectDescs = arrayOfObjectDesc.getObjectDescriptor(); //create list of objDescs and add them to each series while(files.hasNext()){ File file = files.next(); ObjectDescriptor objDesc = new ObjectDescriptor(); Uuid objDescUUID = new Uuid(); objDescUUID.setUuid(UUID.randomUUID().toString()); objDesc.setUuid(objDescUUID); //check mime type objDesc.setMimeType("application/dicom"); Uid uid = new Uid(); String classUID = ""; uid.setUid(classUID); objDesc.setClassUID(uid); String modCode = ""; Modality modality = new Modality(); modality.setModality(modCode); objDesc.setModality(modality); listObjectDescs.add(objDesc); ObjectLocator objLoc = new ObjectLocator(); objLoc.setUuid(objDescUUID); try { objLoc.setUri(file.toURI().toURL().toExternalForm()); //getURI from the iterator } catch (MalformedURLException e) { logger.error(e, e); } objLocators.add(objLoc); } series.setObjectDescriptors(arrayOfObjectDesc); listOfSeries.add(series); study.setSeries(arrayOfSeries); listOfStudies.add(study); patient.setStudies(arrayOfStudy); listPatients.add(patient); availableData.setPatients(arrayOfPatient); ArrayOfObjectDescriptor arrayOfObjectDescTopLevel = new ArrayOfObjectDescriptor(); availableData.setObjectDescriptors(arrayOfObjectDescTopLevel); } WG23DataModelFileSystemImpl dataModel = new WG23DataModelFileSystemImpl(); dataModel.setAvailableData(availableData); ObjectLocator[] objLocs = new ObjectLocator[objLocators.size()]; objLocators.toArray(objLocs); dataModel.setObjectLocators(objLocs); WG23DataModel wg23DataModel = dataModel; return wg23DataModel; } }
package org.csstudio.display.builder.rcp; import static org.csstudio.display.builder.rcp.Plugin.logger; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Optional; import java.util.UUID; import java.util.function.Consumer; import java.util.logging.Level; import org.csstudio.display.builder.model.DisplayModel; import org.csstudio.display.builder.model.macros.Macros; import org.csstudio.display.builder.rcp.run.ContextMenuSupport; import org.csstudio.display.builder.rcp.run.DisplayNavigation; import org.csstudio.display.builder.rcp.run.NavigationAction; import org.csstudio.display.builder.rcp.run.RCP_JFXRepresentation; import org.csstudio.display.builder.rcp.run.ZoomAction; import org.csstudio.display.builder.representation.javafx.JFXRepresentation; import org.csstudio.display.builder.runtime.ActionUtil; import org.csstudio.display.builder.runtime.RuntimeUtil; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IMemento; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IViewReference; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; import javafx.embed.swt.FXCanvas; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.TextArea; /** Part that hosts display builder runtime * * <p>Hosts FXCanvas in SWT * * @author Kay Kasemir */ @SuppressWarnings("nls") public class RuntimeViewPart extends ViewPart { // FXViewPart saves a tiny bit of code, but this allow more control over the FXCanvas. // e4view would allow E4-like POJO, but unclear how representation // would then best find the newly created RuntimeViewPart to set its input etc. // --> Using E3 ViewPart public static final String ID = "org.csstudio.display.builder.rcp.run.RuntimeViewPart"; /** Property on the 'root' Group of the JFX scene that holds RuntimeViewPart */ public static final String ROOT_RUNTIME_VIEW_PART = "_runtime_view_part"; /** Memento key for DisplayInfo */ private static final String MEMENTO_DISPLAY_INFO = "DISPLAY_INFO"; /** Back/forward navigation */ private final DisplayNavigation navigation = new DisplayNavigation(); /** Display info that may have been received from memento */ private Optional<DisplayInfo> display_info = Optional.empty(); private FXCanvas fx_canvas; private RCP_JFXRepresentation representation; private Parent root; private Consumer<DisplayModel> close_handler = ActionUtil::handleClose; private DisplayModel active_model; /** Open a runtime display * @param close_handler Code to call when part is closed * @return {@link RuntimeViewPart} * @throws Exception on error */ public static RuntimeViewPart open(final Consumer<DisplayModel> close_handler) throws Exception { return open(close_handler, null); } /** * Open a runtime display; or, if the display is open, refresh it and makes * its page active * * @param close_handler Code to call when part is closed * @param info DisplayInfo (to compare with currently open displays) * @return {@link RuntimeViewPart} * @throws Exception on error */ public static RuntimeViewPart open(final Consumer<DisplayModel> close_handler, final DisplayInfo info) throws Exception { final IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); if (info != null) for (IViewReference viewRef : page.getViewReferences()) { if (viewRef.getId().startsWith(ID)) { IViewPart viewPart = viewRef.getView(true); if (viewPart instanceof RuntimeViewPart && ((RuntimeViewPart) viewPart).getDisplayInfo().equals(info)) { page.showView(viewRef.getId(), viewRef.getSecondaryId(), IWorkbenchPage.VIEW_ACTIVATE); ((RuntimeViewPart) viewPart).close_handler = close_handler; return (RuntimeViewPart) viewPart; } } } final RuntimeViewPart part = (RuntimeViewPart) page.showView(ID, UUID.randomUUID().toString(), IWorkbenchPage.VIEW_ACTIVATE); part.close_handler = close_handler; return part; } /** Locate the currently active display * @return {@link RuntimeViewPart} or <code>null</code> when nothing found */ public static RuntimeViewPart getActiveDisplay() { final IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); final IWorkbenchPart part = page.getActivePart(); if (part instanceof RuntimeViewPart) return(RuntimeViewPart) part; return null; } public Parent getRoot() { return root; } /** @param name Name of the part */ public void trackCurrentModel(final DisplayModel model) { final DisplayInfo info = new DisplayInfo(model.getUserData(DisplayModel.USER_DATA_INPUT_FILE), model.getName(), model.widgetMacros().getValue()); display_info = Optional.of(info); setPartName(info.getName()); setTitleToolTip(info.getPath()); navigation.setCurrentDisplay(info); active_model = model; } @Override public void init(final IViewSite site, final IMemento memento) throws PartInitException { super.init(site, memento); // Check if previous run persisted DisplayInfo if (memento == null) return; final String serialized_info = memento.getString(MEMENTO_DISPLAY_INFO); if (serialized_info == null) return; try { display_info = Optional.of(DisplayInfoXMLUtil.fromXML(serialized_info)); } catch (Exception ex) { logger.log(Level.WARNING, "Cannot parse model info from " + serialized_info, ex); } } @Override public void createPartControl(final Composite parent) { parent.setLayout(new FillLayout()); fx_canvas = new FXCanvas(parent, SWT.NONE); representation = new RCP_JFXRepresentation(); final Scene scene = new Scene(representation.createModelRoot()); JFXRepresentation.setSceneStyle(scene); root = representation.getModelParent(); root.getProperties().put(ROOT_RUNTIME_VIEW_PART, this); fx_canvas.setScene(scene); JFXCursorFix.apply(scene, fx_canvas); createToolbarItems(); new ContextMenuSupport(getSite(), fx_canvas, representation); parent.addDisposeListener(e -> disposeModel()); // Load persisted DisplayInfo if (display_info.isPresent()) loadDisplayFile(display_info.get()); PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, "org.csstudio.display.builder.editor.rcp.display_builder"); } /** @param zoom Zoom level, 1.0 for 100%, -1 to 'fit' * @return Zoom level actually used */ public double setZoom(final double zoom) { return representation.setZoom(zoom); } @Override public void saveState(final IMemento memento) { // Persist DisplayInfo so it's loaded on application restart final DisplayModel model = active_model; if (model == null) return; final DisplayInfo info = new DisplayInfo(model.getUserData(DisplayModel.USER_DATA_INPUT_FILE), model.getName(), model.widgetMacros().getValue()); try { memento.putString(MEMENTO_DISPLAY_INFO, DisplayInfoXMLUtil.toXML(info)); } catch (Exception ex) { logger.log(Level.WARNING, "Cannot persist display info", ex); } } /** Replace UI content with (error) message * @param message Message to show in the part */ private void showMessage(final String message) { // Assert UI update on UI thread representation.execute(() -> { final Rectangle bounds = fx_canvas.getBounds(); final TextArea text = new TextArea(message); text.setEditable(false); text.setPrefSize(bounds.width, bounds.height); JFXRepresentation.getChildren(root).setAll(text); }); } /** @param message Message to show in the part * @param error Stack trace of error is added to the message */ private void showMessage(final String message, final Throwable error) { final ByteArrayOutputStream buf = new ByteArrayOutputStream(); error.printStackTrace(new PrintStream(buf)); showMessage(message + "\n" + buf.toString()); } /** Load display file, represent it, start runtime * @param info Display file to load */ public void loadDisplayFile(final DisplayInfo info) { showMessage("Loading " + info); // If already executing another display, shut it down disposeModel(); // Load model off UI thread RuntimeUtil.getExecutor().execute(() -> loadModel(info)); } /** @return Info about current display or <code>null</code> */ public DisplayInfo getDisplayInfo() { return display_info.orElse(null); } /** Load display model, schedule representation * @param info Display to load */ private void loadModel(final DisplayInfo info) { try { final DisplayModel model = RuntimeUtil.loadModel(null, info.getPath()); // This code is called // 1) From OpenDisplayAction // No macros in info. // 2) On application restart with DisplayInfo from memento // info contains snapshot of macros from last run // Could simply use info's macros if they are non-empty, // but merging macros with those loaded from model file // allows for newly added macros in the display file. final Macros macros = Macros.merge(model.widgetMacros().getValue(), info.getMacros()); model.widgetMacros().setValue(macros); // Schedule representation on UI thread representation.execute(() -> representModel(model)); } catch (Exception ex) { final String message = "Cannot load " + info; logger.log(Level.SEVERE, message, ex); showMessage(message, ex); } } /** Represent model, schedule start of runtime * @param model Model to represent */ private void representModel(final DisplayModel model) { try { JFXRepresentation.getChildren(root).clear(); representation.representModel(root, model); // Representation for each widget adds a context menu just for the widget. // Add another context menu to scene, tied to the model. fx_canvas.getScene().setOnContextMenuRequested(event -> { event.consume(); representation.fireContextMenu(model); }); } catch (Exception ex) { logger.log(Level.SEVERE, "Cannot represent model", ex); showMessage("Cannot represent model", ex); } // Start runtimes in background RuntimeUtil.getExecutor().execute(() -> RuntimeUtil.startRuntime(model)); } /** Create tool bar entries */ private void createToolbarItems() { final IToolBarManager toolbar = getViewSite().getActionBars().getToolBarManager(); toolbar.add(new ZoomAction(this)); toolbar.add(NavigationAction.createBackAction(this, navigation)); toolbar.add(NavigationAction.createForwardAction(this, navigation)); } /*** Invoke close_handler for model */ private void disposeModel() { final DisplayModel model = active_model; if (model != null && close_handler != null) close_handler.accept(model); } @Override public void setFocus() { fx_canvas.setFocus(); } }
package org.nibiru.ui.core.impl.builder; import org.nibiru.ui.core.api.RelativePanel; import org.nibiru.ui.core.api.RelativePanel.Rule; import org.nibiru.ui.core.api.Widget; import javax.inject.Inject; import static com.google.common.base.Preconditions.checkNotNull; public class RelativePanelBuilder extends BaseContainerBuilder<RelativePanel, RelativePanelBuilder> { @Inject public RelativePanelBuilder(RelativePanel relativePanel) { super(relativePanel); } public RelativePanelBuilder addRule(Rule rule) { checkNotNull(rule); object.addRule(rule); return this; } public RuleBuilder prepare(Widget widget) { checkNotNull(widget); return new RuleBuilder(widget); } public interface RuleProvider { Rule getRule(Widget target, RelativePanel container); } public class RuleBuilder { private final Widget target; private RuleBuilder(Widget target) { this.target = target; } public RuleBuilder above() { object.addAbove(target, null); return this; } public RuleBuilder above(Widget source) { checkNotNull(source); object.addAbove(target, source); return this; } public RuleBuilder alignBottom() { object.addAlignBottom(target, null); return this; } public RuleBuilder alignBottom(Widget source) { checkNotNull(source); object.addAlignBottom(target, source); return this; } public RuleBuilder alignLeft() { object.addAlignLeft(target, null); return this; } public RuleBuilder alignLeft(Widget source) { checkNotNull(source); object.addAlignLeft(target, source); return this; } public RuleBuilder alignRight() { object.addAlignRight(target, null); return this; } public RuleBuilder alignRight(Widget source) { checkNotNull(source); object.addAlignRight(target, source); return this; } public RuleBuilder alignTop() { object.addAlignTop(target, null); return this; } public RuleBuilder alignTop(Widget source) { checkNotNull(source); object.addAlignTop(target, source); return this; } public RuleBuilder below() { object.addBelow(target, null); return this; } public RuleBuilder below(Widget source) { checkNotNull(source); object.addBelow(target, source); return this; } public RuleBuilder centerHorizontally() { object.addCenterHorizontally(target, null); return this; } public RuleBuilder centerHorizontally(Widget source) { checkNotNull(source); object.addCenterHorizontally(target, source); return this; } public RuleBuilder centerVertically() { object.addCenterVertically(target, null); return this; } public RuleBuilder centerVertically(Widget source) { checkNotNull(source); object.addCenterVertically(target, source); return this; } public RuleBuilder matchBottomWithBottom() { object.addMatchBottomWithBottom(target, null); return this; } public RuleBuilder matchBottomWithBottom(Widget source) { checkNotNull(source); object.addMatchBottomWithBottom(target, source); return this; } public RuleBuilder matchBottomWithTop() { object.addMatchBottomWithTop(target, null); return this; } public RuleBuilder matchBottomWithTop(Widget source) { checkNotNull(source); object.addMatchBottomWithTop(target, source); return this; } public RuleBuilder matchHeight() { object.addMatchHeight(target, null); return this; } public RuleBuilder matchHeight(Widget source) { checkNotNull(source); object.addMatchHeight(target, source); return this; } public RuleBuilder matchLeftWithLeft() { object.addMatchLeftWithLeft(target, null); return this; } public RuleBuilder matchLeftWithLeft(Widget source) { checkNotNull(source); object.addMatchLeftWithLeft(target, source); return this; } public RuleBuilder matchLeftWithRight() { object.addMatchLeftWithRight(target, null); return this; } public RuleBuilder matchLeftWithRight(Widget source) { checkNotNull(source); object.addMatchLeftWithRight(target, source); return this; } public RuleBuilder matchRightWithLeft() { object.addMatchRightWithLeft(target, null); return this; } public RuleBuilder matchRightWithLeft(Widget source) { checkNotNull(source); object.addMatchRightWithLeft(target, source); return this; } public RuleBuilder matchRightWithRight() { object.addMatchRightWithRight(target, null); return this; } public RuleBuilder matchRightWithRight(Widget source) { checkNotNull(source); object.addMatchRightWithRight(target, source); return this; } public RuleBuilder matchTopWithBottom() { object.addMatchTopWithBottom(target, null); return this; } public RuleBuilder matchTopWithBottom(Widget source) { checkNotNull(source); object.addMatchTopWithBottom(target, source); return this; } public RuleBuilder matchTopWithTop() { object.addMatchTopWithTop(target, null); return this; } public RuleBuilder matchTopWithTop(Widget source) { checkNotNull(source); object.addMatchTopWithTop(target, source); return this; } public RuleBuilder matchWidth() { object.addMatchWidth(target, null); return this; } public RuleBuilder matchWidth(Widget source) { checkNotNull(source); object.addMatchWidth(target, source); return this; } public RuleBuilder toLeftOf() { object.addToLeftOf(target, null); return this; } public RuleBuilder toLeftOf(Widget source) { checkNotNull(source); object.addToLeftOf(target, source); return this; } public RuleBuilder toRightOf() { object.addToRightOf(target, null); return this; } public RuleBuilder toRightOf(Widget source) { checkNotNull(source); object.addToRightOf(target, source); return this; } public RuleBuilder custom(RuleProvider ruleProvider) { checkNotNull(ruleProvider); object.addRule(ruleProvider.getRule(target, object)); return this; } public RelativePanelBuilder add() { RelativePanelBuilder.this.add(target); return RelativePanelBuilder.this; } } }
package com.intellij.execution.actions; import com.intellij.execution.ProgramRunnerUtil; import com.intellij.execution.RunnerAndConfigurationSettings; import com.intellij.execution.configurations.ConfigurationType; import com.intellij.execution.configurations.LocatableConfiguration; import com.intellij.execution.configurations.LocatableConfigurationBase; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.execution.lineMarker.RunLineMarkerProvider; import com.intellij.ide.IdeEventQueue; import com.intellij.ide.macro.MacroManager; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.util.ProgressIndicatorUtils; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ThreeState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.function.Supplier; public abstract class BaseRunConfigurationAction extends ActionGroup { protected static final Logger LOG = Logger.getInstance(BaseRunConfigurationAction.class); protected BaseRunConfigurationAction(@NotNull Supplier<String> text, @NotNull Supplier<String> description, final Icon icon) { super(text, description, icon); setPopup(true); setEnabledInModalContext(true); } @Override public AnAction @NotNull [] getChildren(@Nullable AnActionEvent e) { return e != null ? getChildren(e.getDataContext()) : EMPTY_ARRAY; } private AnAction[] getChildren(DataContext dataContext) { final ConfigurationContext context = ConfigurationContext.getFromContext(dataContext); if (!Registry.is("suggest.all.run.configurations.from.context") && context.findExisting() != null) { return EMPTY_ARRAY; } return createChildActions(context, getConfigurationsFromContext(context)).toArray(EMPTY_ARRAY); } @NotNull protected List<AnAction> createChildActions(@NotNull ConfigurationContext context, @NotNull List<? extends ConfigurationFromContext> configurations) { if (configurations.size() <= 1) { return Collections.emptyList(); } final List<AnAction> childActions = new ArrayList<>(); for (final ConfigurationFromContext fromContext : configurations) { final ConfigurationType configurationType = fromContext.getConfigurationType(); final String actionName = childActionName(fromContext); final AnAction anAction = new AnAction(actionName, configurationType.getDisplayName(), fromContext.getConfiguration().getIcon()) { @Override public void actionPerformed(@NotNull AnActionEvent e) { perform(fromContext, context); } }; anAction.getTemplatePresentation().setText(actionName, false); childActions.add(anAction); } return childActions; } @NotNull private List<ConfigurationFromContext> getConfigurationsFromContext(ConfigurationContext context) { final List<ConfigurationFromContext> fromContext = context.getConfigurationsFromContext(); if (fromContext == null) { return Collections.emptyList(); } final List<ConfigurationFromContext> enabledConfigurations = new ArrayList<>(); for (ConfigurationFromContext configurationFromContext : fromContext) { if (isEnabledFor(configurationFromContext.getConfiguration())) { enabledConfigurations.add(configurationFromContext); } } return enabledConfigurations; } protected boolean isEnabledFor(RunConfiguration configuration) { return true; } @Override public boolean canBePerformed(@NotNull DataContext dataContext) { Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project != null && DumbService.isDumb(project)) { return false; } final ConfigurationContext context = ConfigurationContext.getFromContext(dataContext); final RunnerAndConfigurationSettings existing = context.findExisting(); if (existing == null) { final List<ConfigurationFromContext> fromContext = getConfigurationsFromContext(context); return fromContext.size() <= 1; } return true; } @Override public void actionPerformed(@NotNull final AnActionEvent e) { final DataContext dataContext = e.getDataContext(); MacroManager.getInstance().cacheMacrosPreview(e.getDataContext()); final ConfigurationContext context = ConfigurationContext.getFromContext(dataContext); final RunnerAndConfigurationSettings existing = context.findExisting(); if (existing == null) { final List<ConfigurationFromContext> producers = getConfigurationsFromContext(context); if (producers.isEmpty()) return; perform(producers.get(0), context); return; } if (LOG.isDebugEnabled()) { String configurationClass = existing.getConfiguration().getClass().getName(); LOG.debug(String.format("Use existing run configuration: %s", configurationClass)); } perform(context); } private void perform(final ConfigurationFromContext configurationFromContext, final ConfigurationContext context) { RunnerAndConfigurationSettings configurationSettings = configurationFromContext.getConfigurationSettings(); context.setConfiguration(configurationSettings); configurationFromContext.onFirstRun(context, () -> { if (LOG.isDebugEnabled()) { RunnerAndConfigurationSettings settings = context.getConfiguration(); RunConfiguration configuration = settings == null ? null : settings.getConfiguration(); String configurationClass = configuration == null ? null : configuration.getClass().getName(); LOG.debug(String.format("Create run configuration: %s", configurationClass)); } perform(context); }); } protected abstract void perform(ConfigurationContext context); @Override public void beforeActionPerformedUpdate(@NotNull AnActionEvent e) { fullUpdate(e); } @Nullable private static Integer ourLastTimeoutStamp = null; @Override public void update(@NotNull final AnActionEvent event) { VirtualFile vFile = event.getDataContext().getData(CommonDataKeys.VIRTUAL_FILE); ThreeState hadAnythingRunnable = vFile == null ? ThreeState.UNSURE : RunLineMarkerProvider.hadAnythingRunnable(vFile); if (hadAnythingRunnable == ThreeState.UNSURE) { fullUpdate(event); return; } boolean success = !alreadyExceededTimeoutOnSimilarAction() && ProgressIndicatorUtils.withTimeout(Registry.intValue("run.configuration.update.timeout"), () -> { fullUpdate(event); return true; }) != null; if (!success) { recordUpdateTimeout(); approximatePresentationByPreviousAvailability(event, hadAnythingRunnable); } } private static boolean alreadyExceededTimeoutOnSimilarAction() { return Objects.equals(IdeEventQueue.getInstance().getEventCount(), ourLastTimeoutStamp); } private static void recordUpdateTimeout() { ourLastTimeoutStamp = IdeEventQueue.getInstance().getEventCount(); } // we assume that presence of anything runnable in a file changes rarely, so using last recorded state is mostly OK protected void approximatePresentationByPreviousAvailability(AnActionEvent event, ThreeState hadAnythingRunnable) { event.getPresentation().copyFrom(getTemplatePresentation()); event.getPresentation().setEnabledAndVisible(hadAnythingRunnable == ThreeState.YES); } protected void fullUpdate(@NotNull AnActionEvent event) { final ConfigurationContext context = ConfigurationContext.getFromContext(event.getDataContext()); final Presentation presentation = event.getPresentation(); final RunnerAndConfigurationSettings existing = context.findExisting(); RunnerAndConfigurationSettings configuration = existing; if (configuration == null) { configuration = context.getConfiguration(); } if (configuration == null){ presentation.setEnabledAndVisible(false); } else{ presentation.setEnabledAndVisible(true); VirtualFile vFile = event.getDataContext().getData(CommonDataKeys.VIRTUAL_FILE); if (vFile != null) { RunLineMarkerProvider.markRunnable(vFile, true); } final List<ConfigurationFromContext> fromContext = getConfigurationsFromContext(context); if (existing == null && !fromContext.isEmpty()) { //todo[nik,anna] it's dirty fix. Otherwise wrong configuration will be returned from context.getConfiguration() context.setConfiguration(fromContext.get(0).getConfigurationSettings()); } final String name = suggestRunActionName((LocatableConfiguration)configuration.getConfiguration()); updatePresentation(presentation, existing != null || fromContext.size() <= 1 ? name : "", context); } } @Override public boolean isDumbAware() { return false; } @NotNull public static String suggestRunActionName(@NotNull LocatableConfiguration configuration) { if (configuration instanceof LocatableConfigurationBase && configuration.isGeneratedName()) { String actionName = ((LocatableConfigurationBase<?>)configuration).getActionName(); if (actionName != null) { return actionName; } } return ProgramRunnerUtil.shortenName(configuration.getName(), 0); } @NotNull private static String childActionName(ConfigurationFromContext configurationFromContext) { RunConfiguration configuration = configurationFromContext.getConfiguration(); if (!(configuration instanceof LocatableConfiguration)) { return configurationFromContext.getConfigurationType().getDisplayName(); } if (configurationFromContext.isFromAlternativeLocation()) { String locationDisplayName = configurationFromContext.getAlternativeLocationDisplayName(); if (locationDisplayName != null) { return ((LocatableConfigurationBase<?>)configuration).getActionName() + " " + locationDisplayName; } } return StringUtil.unquoteString(suggestRunActionName((LocatableConfiguration)configurationFromContext.getConfiguration())); } protected abstract void updatePresentation(Presentation presentation, @NotNull String actionText, ConfigurationContext context); }
package com.intellij.application.options; import com.intellij.openapi.components.PathMacroMap; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.StringUtilRt; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtilRt; import com.intellij.util.containers.hash.LinkedHashMap; import gnu.trove.TObjectIntHashMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.model.serialization.PathMacroUtil; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author Eugene Zhuravlev * * @see PathMacrosImpl#addMacroReplacements(ReplacePathToMacroMap) * @see com.intellij.openapi.components.PathMacroManager */ public class ReplacePathToMacroMap extends PathMacroMap { private List<String> myPathsIndex = null; private final Map<String, String> myMacroMap = ContainerUtilRt.newLinkedHashMap(); @NonNls public static final String[] PROTOCOLS; static { List<String> protocols = new ArrayList<>(); protocols.add("file"); protocols.add("jar"); if (Extensions.getRootArea().hasExtensionPoint(PathMacroExpandableProtocolBean.EP_NAME.getName())) { for (PathMacroExpandableProtocolBean bean : PathMacroExpandableProtocolBean.EP_NAME.getExtensions()) { protocols.add(bean.protocol); } } PROTOCOLS = ArrayUtil.toStringArray(protocols); } public void addMacroReplacement(String path, String macroName) { addReplacement(FileUtil.toSystemIndependentName(path), "$" + macroName + "$", true); } public void addReplacement(String path, String macroExpr, boolean overwrite) { path = StringUtil.trimEnd(path, "/"); putIfAbsent(path, macroExpr, overwrite); for (String protocol : PROTOCOLS) { putIfAbsent(protocol + ":" + path, protocol + ":" + macroExpr, overwrite); putIfAbsent(protocol + ":/" + path, protocol + ":/" + macroExpr, overwrite); putIfAbsent(protocol + "://" + path, protocol + "://" + macroExpr, overwrite); } } private void putIfAbsent(final String path, final String substitution, final boolean overwrite) { if (overwrite || !myMacroMap.containsKey(path)) { myMacroMap.put(path, substitution); } } @Override public String substitute(@Nullable String text, boolean caseSensitive) { if (text == null) { return null; } for (final String path : getPathIndex()) { text = replacePathMacro(text, path, caseSensitive); } return text; } private String replacePathMacro(@NotNull String text, @NotNull final String path, boolean caseSensitive) { if (text.length() < path.length() || path.isEmpty()) { return text; } if (!(caseSensitive ? text.startsWith(path) : StringUtilRt.startsWithIgnoreCase(text, path))) { return text; } //check that this is complete path (ends with "/" or "!/") // do not collapse partial paths, i.e. do not substitute "/a/b/cd" in paths like "/a/b/cdeFgh" int endOfOccurrence = path.length(); final boolean isWindowsRoot = path.endsWith(":/"); if (!isWindowsRoot && endOfOccurrence < text.length() && text.charAt(endOfOccurrence) != '/' && !(text.charAt(endOfOccurrence) == '!' && text.substring(endOfOccurrence).startsWith("!/"))) { return text; } String s = myMacroMap.get(path); if (text.length() > endOfOccurrence) { return s + text.substring(endOfOccurrence); } else { return s; } } @NotNull @Override public String substituteRecursively(@NotNull String text, final boolean caseSensitive) { for (final String path : getPathIndex()) { text = replacePathMacroRecursively(text, path, caseSensitive); } return text; } private String replacePathMacroRecursively(@NotNull final String text, @NotNull final String path, boolean caseSensitive) { if (text.length() < path.length()) { return text; } if (path.isEmpty()) return text; final StringBuilder newText = new StringBuilder(); final boolean isWindowsRoot = path.endsWith(":/"); int i = 0; while (i < text.length()) { int occurrenceOfPath = caseSensitive ? text.indexOf(path, i) : StringUtil.indexOfIgnoreCase(text, path, i); if (occurrenceOfPath >= 0) { int endOfOccurrence = occurrenceOfPath + path.length(); if (!isWindowsRoot && endOfOccurrence < text.length() && text.charAt(endOfOccurrence) != '/' && text.charAt(endOfOccurrence) != '\"' && text.charAt(endOfOccurrence) != ' ' && !text.substring(endOfOccurrence).startsWith("!/")) { newText.append(text, i, endOfOccurrence); i = endOfOccurrence; continue; } if (occurrenceOfPath > 0) { char prev = text.charAt(occurrenceOfPath - 1); if (Character.isLetterOrDigit(prev) || prev == '_') { newText.append(text, i, endOfOccurrence); i = endOfOccurrence; continue; } } } if (occurrenceOfPath < 0) { if (newText.length() == 0) { return text; } newText.append(text.substring(i)); break; } else { newText.append(text, i, occurrenceOfPath); newText.append(myMacroMap.get(path)); i = occurrenceOfPath + path.length(); } } return newText.toString(); } private static int getIndex(@NotNull String replacement) { if (replacement.contains("..")) return 1; if (replacement.contains("$" + PathMacroUtil.USER_HOME_NAME + "$")) return 1; if (replacement.contains("$" + PathMacroUtil.APPLICATION_HOME_DIR + "$")) return 1; if (replacement.contains(PathMacroUtil.DEPRECATED_MODULE_DIR)) return 3; if (replacement.contains("$" + PathMacroUtil.PROJECT_DIR_MACRO_NAME + "$")) return 3; return 2; } private static int stripPrefix(@NotNull String key) { key = StringUtil.trimStart(key, "jar:"); key = StringUtil.trimStart(key, "file:"); while (key.startsWith("/")) { key = key.substring(1); } return key.length(); } @NotNull public List<String> getPathIndex() { if (myPathsIndex == null || myPathsIndex.size() != myMacroMap.size()) { List<Map.Entry<String, String>> entries = new ArrayList<>(myMacroMap.entrySet()); final TObjectIntHashMap<String> weights = new TObjectIntHashMap<>(entries.size()); for (Map.Entry<String, String> entry : entries) { weights.put(entry.getKey(), getIndex(entry.getValue()) * 512 + stripPrefix(entry.getKey())); } entries.sort((o1, o2) -> weights.get(o2.getKey()) - weights.get(o1.getKey())); myPathsIndex = ContainerUtilRt.map2List(entries, entry -> entry.getKey()); } return myPathsIndex; } public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof ReplacePathToMacroMap)) return false; return myMacroMap.equals(((ReplacePathToMacroMap)obj).myMacroMap); } public int hashCode() { return myMacroMap.hashCode(); } public void put(String path, String replacement) { myMacroMap.put(path, replacement); } }
package com.intellij.structuralsearch.plugin.ui; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.codeInsight.template.impl.Variable; import com.intellij.find.FindBundle; import com.intellij.find.FindSettings; import com.intellij.ide.IdeBundle; import com.intellij.ide.util.scopeChooser.ScopeChooserCombo; import com.intellij.lang.Language; import com.intellij.lang.LanguageUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.application.Result; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.fileTypes.impl.FileTypeRenderer; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerListener; import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowId; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.SearchScope; import com.intellij.structuralsearch.*; import com.intellij.structuralsearch.plugin.StructuralSearchPlugin; import com.intellij.ui.ComboboxSpeedSearch; import com.intellij.ui.IdeBorderFactory; import com.intellij.ui.ListCellRendererWrapper; import com.intellij.ui.TitledSeparator; import com.intellij.util.Alarm; import com.intellij.util.ui.JBUI; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.*; import java.util.List; /** * Class to show the user the request for search */ public class SearchDialog extends DialogWrapper { protected SearchContext searchContext; // text for search protected Editor searchCriteriaEdit; // options of search scope private ScopeChooserCombo myScopeChooserCombo; private JCheckBox recursiveMatching; private JCheckBox caseSensitiveMatch; private JComboBox<FileType> fileTypes; private JComboBox<String> contexts; private JComboBox<Language> dialects; private JLabel status; private JLabel statusText; protected Configuration myConfiguration; private JCheckBox openInNewTab; private final Alarm myAlarm; public static final String USER_DEFINED = SSRBundle.message("new.template.defaultname"); private boolean useLastConfiguration; @NonNls private FileType ourFtSearchVariant = StructuralSearchUtil.getDefaultFileType(); private static Language ourDialect = null; private static String ourContext = null; private final boolean myShowScopePanel; private final boolean myRunFindActionOnClose; private boolean myDoingOkAction; private String mySavedEditorText; private JPanel myContentPanel; private JComponent myEditorPanel; public SearchDialog(SearchContext searchContext) { this(searchContext, true, true); } public SearchDialog(SearchContext searchContext, boolean showScope, boolean runFindActionOnClose) { super(searchContext.getProject(), true); if (showScope) setModal(false); myShowScopePanel = showScope; myRunFindActionOnClose = runFindActionOnClose; this.searchContext = searchContext; setTitle(getDefaultTitle()); if (runFindActionOnClose) { setOKButtonText(FindBundle.message("find.dialog.find.button")); } myConfiguration = createConfiguration(null); init(); myAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, myDisposable); ProjectManager.getInstance().addProjectManagerListener(searchContext.getProject(), new ProjectManagerListener() { @Override public void projectClosing(Project project) { close(CANCEL_EXIT_CODE); } }); } public void setUseLastConfiguration(boolean useLastConfiguration) { this.useLastConfiguration = useLastConfiguration; } void setSearchPattern(final Configuration config) { setValuesFromConfig(config); initiateValidation(); } protected Editor createEditor(final SearchContext searchContext, String text) { Editor editor = null; if (fileTypes != null) { final FileType fileType = (FileType)fileTypes.getSelectedItem(); final Language dialect = (Language)dialects.getSelectedItem(); final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(fileType); if (profile != null) { editor = profile.createEditor(searchContext, fileType, dialect, text, useLastConfiguration); } } if (editor == null) { final EditorFactory factory = EditorFactory.getInstance(); final Document document = factory.createDocument(""); editor = factory.createEditor(document, searchContext.getProject()); editor.getSettings().setFoldingOutlineShown(false); } editor.getDocument().addDocumentListener(new DocumentListener() { @Override public void documentChanged(final DocumentEvent event) { initiateValidation(); } }); return editor; } void initiateValidation() { myAlarm.cancelAllRequests(); myAlarm.addRequest(() -> { final boolean valid = ReadAction.compute(() -> { try { return Boolean.valueOf(isValid()); } catch (ProcessCanceledException e) { throw e; } catch (RuntimeException e) { Logger.getInstance(SearchDialog.class).error(e); } return Boolean.FALSE; }).booleanValue(); ApplicationManager.getApplication().invokeLater(() -> getOKAction().setEnabled(valid)); }, 250); } protected void buildOptions(JPanel searchOptions) { recursiveMatching = new JCheckBox(SSRBundle.message("recursive.matching.checkbox"), true); if (isRecursiveSearchEnabled()) { searchOptions.add(UIUtil.createOptionLine(recursiveMatching)); } caseSensitiveMatch = new JCheckBox(FindBundle.message("find.options.case.sensitive"), true); searchOptions.add(UIUtil.createOptionLine(caseSensitiveMatch)); final List<FileType> types = new ArrayList<>(); for (FileType fileType : StructuralSearchUtil.getSuitableFileTypes()) { if (StructuralSearchUtil.getProfileByFileType(fileType) != null) { types.add(fileType); } } Collections.sort(types, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName())); final DefaultComboBoxModel<FileType> comboBoxModel = new DefaultComboBoxModel<>(types.toArray(FileType.EMPTY_ARRAY)); fileTypes = new ComboBox<>(comboBoxModel); fileTypes.setRenderer(new FileTypeRenderer()); new ComboboxSpeedSearch(fileTypes) { @Override protected String getElementText(Object element) { return ((FileType)element).getName(); } }; contexts = new ComboBox<>(60); dialects = new ComboBox<>(120); dialects.setRenderer(new ListCellRendererWrapper<Language>() { @Override public void customize(JList list, Language value, int index, boolean selected, boolean hasFocus) { if (value == null) { setText("None"); } else { setText(value.getDisplayName()); } } }); dialects.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { updateEditor(); } }); new ComboboxSpeedSearch(dialects); final JLabel jLabel = new JLabel(SSRBundle.message("search.dialog.file.type.label")); final JLabel jLabel2 = new JLabel(SSRBundle.message("search.dialog.context.label")); final JLabel jLabel3 = new JLabel(SSRBundle.message("search.dialog.file.dialect.label")); searchOptions.add( UIUtil.createOptionLine( new JComponent[]{ jLabel, fileTypes, (JComponent)Box.createHorizontalStrut(8), jLabel2, contexts, (JComponent)Box.createHorizontalStrut(8), jLabel3, dialects, } ) ); jLabel.setLabelFor(fileTypes); jLabel2.setLabelFor(contexts); jLabel3.setLabelFor(dialects); detectFileTypeAndDialect(); fileTypes.setSelectedItem(ourFtSearchVariant); fileTypes.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { updateDialectsAndContexts(); updateEditor(); initiateValidation(); } } }); dialects.setSelectedItem(ourDialect); contexts.setSelectedItem(ourContext); updateDialectsAndContexts(); } void updateEditor() { if (myContentPanel != null) { if (myEditorPanel != null) { myContentPanel.remove(myEditorPanel); } disposeEditorContent(); myEditorPanel = createEditorContent(); myContentPanel.add(myEditorPanel, BorderLayout.CENTER); myContentPanel.revalidate(); searchCriteriaEdit.putUserData(SubstitutionShortInfoHandler.CURRENT_CONFIGURATION_KEY, myConfiguration); } } void updateDialectsAndContexts() { final FileType fileType = (FileType)fileTypes.getSelectedItem(); if (fileType instanceof LanguageFileType) { Language language = ((LanguageFileType)fileType).getLanguage(); Language[] languageDialects = LanguageUtil.getLanguageDialects(language); Arrays.sort(languageDialects, Comparator.comparing(Language::getDisplayName)); Language[] variants = new Language[languageDialects.length + 1]; variants[0] = null; System.arraycopy(languageDialects, 0, variants, 1, languageDialects.length); dialects.setModel(new DefaultComboBoxModel<>(variants)); dialects.setEnabled(variants.length > 1); } final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(fileType); if (profile instanceof StructuralSearchProfileBase) { final String[] contextNames = ((StructuralSearchProfileBase)profile).getContextNames(); if (contextNames.length > 0) { contexts.setModel(new DefaultComboBoxModel<>(contextNames)); contexts.setSelectedItem(contextNames[0]); contexts.setEnabled(true); return; } } contexts.setSelectedItem(null); contexts.setEnabled(false); } private void detectFileTypeAndDialect() { final PsiFile file = searchContext.getFile(); if (file != null) { PsiElement context = null; if (searchContext.getEditor() != null) { context = file.findElementAt(searchContext.getEditor().getCaretModel().getOffset()); if (context != null) { context = context.getParent(); } } if (context == null) { context = file; } FileType detectedFileType = null; StructuralSearchProfile profile = StructuralSearchUtil.getProfileByPsiElement(context); if (profile != null) { FileType fileType = profile.detectFileType(context); if (fileType != null) { detectedFileType = fileType; } } if (detectedFileType == null) { for (FileType fileType : StructuralSearchUtil.getSuitableFileTypes()) { if (fileType instanceof LanguageFileType && ((LanguageFileType)fileType).getLanguage().equals(context.getLanguage())) { detectedFileType = fileType; break; } } } ourFtSearchVariant = detectedFileType != null ? detectedFileType : StructuralSearchUtil.getDefaultFileType(); } } protected boolean isRecursiveSearchEnabled() { return myShowScopePanel; } public void setValuesFromConfig(Configuration configuration) { myConfiguration = createConfiguration(configuration); setDialogTitle(myConfiguration); final MatchOptions matchOptions = myConfiguration.getMatchOptions(); UIUtil.setContent(searchCriteriaEdit, matchOptions.getSearchPattern()); recursiveMatching.setSelected(isRecursiveSearchEnabled() && matchOptions.isRecursiveSearch()); caseSensitiveMatch.setSelected(matchOptions.isCaseSensitiveMatch()); fileTypes.setSelectedItem(matchOptions.getFileType()); dialects.setSelectedItem(matchOptions.getDialect()); if (matchOptions.getPatternContext() != null) { contexts.setSelectedItem(matchOptions.getPatternContext()); } searchCriteriaEdit.putUserData(SubstitutionShortInfoHandler.CURRENT_CONFIGURATION_KEY, myConfiguration); } void setDialogTitle(final Configuration configuration) { setTitle(getDefaultTitle() + " - " + configuration.getName()); } public Configuration createConfiguration(Configuration template) { return (template == null) ? new SearchConfiguration(USER_DEFINED, USER_DEFINED) : new SearchConfiguration(template); } protected void setText(String text) { setTextForEditor(text, searchCriteriaEdit); } protected final void setTextForEditor(final String selection, Editor editor) { final Project project = searchContext.getProject(); UIUtil.setContent(editor, selection); final Document document = editor.getDocument(); editor.getSelectionModel().setSelection(0, document.getTextLength()); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); documentManager.commitDocument(document); final PsiFile file = documentManager.getPsiFile(document); if (file == null) return; new WriteCommandAction(project, file) { @Override protected void run(@NotNull Result result) { CodeStyleManager.getInstance(project).adjustLineIndent(file, new TextRange(0, document.getTextLength())); } }.execute(); } protected void startSearching() { new SearchCommand(myConfiguration, searchContext).startSearching(); } protected String getDefaultTitle() { return SSRBundle.message("structural.search.title"); } protected JComponent createEditorContent() { final JPanel result = new JPanel(new BorderLayout()); searchCriteriaEdit = createEditor(searchContext, mySavedEditorText != null ? mySavedEditorText : ""); result.add(BorderLayout.CENTER, searchCriteriaEdit.getComponent()); result.setMinimumSize(new Dimension(150, 100)); final JPanel labelPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 0)); labelPanel.add(new JLabel(SSRBundle.message("search.template"))); labelPanel.add(UIUtil.createCompleteMatchInfo(() -> myConfiguration)); result.add(BorderLayout.NORTH, labelPanel); return result; } protected int getRowsCount() { return 4; } @Override protected JComponent createCenterPanel() { myContentPanel = new JPanel(new BorderLayout()); myEditorPanel = createEditorContent(); myContentPanel.add(BorderLayout.CENTER, myEditorPanel); myContentPanel.add(BorderLayout.SOUTH, Box.createVerticalStrut(8)); JComponent centerPanel = new JPanel(new BorderLayout()); { JPanel panel = new JPanel(new BorderLayout()); panel.add(BorderLayout.CENTER, myContentPanel); panel.add(BorderLayout.SOUTH, createTemplateManagementButtons()); centerPanel.add(BorderLayout.CENTER, panel); } JPanel optionsContent = new JPanel(new BorderLayout()); centerPanel.add(BorderLayout.SOUTH, optionsContent); JPanel searchOptions = new JPanel(); searchOptions.setLayout(new GridLayout(getRowsCount(), 1, 0, 0)); searchOptions.setBorder(IdeBorderFactory.createTitledBorder(SSRBundle.message("ssdialog.options.group.border"), true)); JPanel allOptions = new JPanel(new BorderLayout()); if (myShowScopePanel) { myScopeChooserCombo = new ScopeChooserCombo( searchContext.getProject(), true, false, FindSettings.getInstance().getDefaultScopeName() ); Disposer.register(myDisposable, myScopeChooserCombo); JPanel scopePanel = new JPanel(new GridBagLayout()); TitledSeparator separator = new TitledSeparator(SSRBundle.message("search.dialog.scope.label"), myScopeChooserCombo.getComboBox()); scopePanel.add(separator, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, JBUI.insetsTop(5), 0, 0)); scopePanel.add(myScopeChooserCombo, new GridBagConstraints(0, 1, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, JBUI.insetsLeft(10), 0, 0)); allOptions.add( scopePanel, BorderLayout.SOUTH ); myScopeChooserCombo.getComboBox().addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { initiateValidation(); } }); } else { myScopeChooserCombo = null; } buildOptions(searchOptions); allOptions.add(searchOptions, BorderLayout.CENTER); optionsContent.add(allOptions, BorderLayout.CENTER); if (myRunFindActionOnClose) { JPanel panel = new JPanel(new BorderLayout()); panel.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0)); openInNewTab = new JCheckBox(FindBundle.message("find.open.in.new.tab.checkbox")); openInNewTab.setSelected(FindSettings.getInstance().isShowResultsInSeparateView()); ToolWindow findWindow = ToolWindowManager.getInstance(searchContext.getProject()).getToolWindow(ToolWindowId.FIND); openInNewTab.setEnabled(findWindow != null && findWindow.isAvailable()); panel.add(openInNewTab, BorderLayout.EAST); optionsContent.add(BorderLayout.SOUTH, panel); } updateEditor(); return centerPanel; } @Override protected JComponent createSouthPanel() { final JPanel statusPanel = new JPanel(new BorderLayout(5, 0)); statusPanel.add(super.createSouthPanel(), BorderLayout.NORTH); statusPanel.add(statusText = new JLabel(SSRBundle.message("status.message")), BorderLayout.WEST); statusPanel.add(status = new JLabel(), BorderLayout.CENTER); status.setMinimumSize(new Dimension(0, 0)); return statusPanel; } private JPanel createTemplateManagementButtons() { JPanel panel = new JPanel(null); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); panel.add(Box.createHorizontalGlue()); panel.add( createJButtonForAction(new AbstractAction() { { putValue(NAME, SSRBundle.message("save.template.text.button")); } @Override public void actionPerformed(ActionEvent e) { final Configuration configuration = getConfiguration(); if (!ConfigurationManager.getInstance(getProject()).showSaveTemplateAsDialog(configuration)) { return; } setDialogTitle(configuration); } }) ); panel.add(Box.createHorizontalStrut(8)); panel.add( createJButtonForAction( new AbstractAction() { { putValue(NAME, SSRBundle.message("edit.variables.button")); } @Override public void actionPerformed(ActionEvent e) { new EditVarConstraintsDialog( searchContext.getProject(), myConfiguration, getVariablesFromListeners(), (FileType)fileTypes.getSelectedItem() ).show(); initiateValidation(); } } ) ); panel.add(Box.createHorizontalStrut(8)); panel.add( createJButtonForAction( new AbstractAction() { { putValue(NAME, SSRBundle.message("history.button")); } @Override public void actionPerformed(ActionEvent e) { SelectTemplateDialog dialog = new SelectTemplateDialog(searchContext.getProject(), true, isReplaceDialog()); if (!dialog.showAndGet()) { return; } Configuration[] configurations = dialog.getSelectedConfigurations(); if (configurations.length == 1) { setSearchPattern(configurations[0]); } } } ) ); panel.add(Box.createHorizontalStrut(8)); panel.add( createJButtonForAction( new AbstractAction() { { putValue(NAME, SSRBundle.message("copy.existing.template.button")); } @Override public void actionPerformed(ActionEvent e) { SelectTemplateDialog dialog = new SelectTemplateDialog(searchContext.getProject(), false, isReplaceDialog()); if (!dialog.showAndGet()) { return; } Configuration[] configurations = dialog.getSelectedConfigurations(); if (configurations.length == 1) { setSearchPattern(configurations[0]); } } } ) ); return panel; } protected List<Variable> getVariablesFromListeners() { return getVarsFrom(searchCriteriaEdit); } protected static List<Variable> getVarsFrom(Editor searchCriteriaEdit) { SubstitutionShortInfoHandler handler = SubstitutionShortInfoHandler.retrieve(searchCriteriaEdit); return (handler == null) ? new ArrayList<>() : new ArrayList<>(handler.getVariables()); } public final Project getProject() { return searchContext.getProject(); } protected boolean isReplaceDialog() { return false; } @Override public void show() { StructuralSearchPlugin.getInstance(getProject()).setDialogVisible(true); if (!useLastConfiguration) { final Editor editor = searchContext.getEditor(); boolean setSomeText = false; if (editor != null) { final SelectionModel selectionModel = editor.getSelectionModel(); if (selectionModel.hasSelection()) { setText(selectionModel.getSelectedText()); setSomeText = true; } } if (!setSomeText) { final Configuration configuration = ConfigurationManager.getInstance(getProject()).getMostRecentConfiguration(); if (configuration != null) { setValuesFromConfig(configuration); } } } initiateValidation(); super.show(); } @Override public JComponent getPreferredFocusedComponent() { return searchCriteriaEdit.getContentComponent(); } @Override protected void doOKAction() { myDoingOkAction = true; final boolean result = isValid(); myDoingOkAction = false; if (!result) return; myAlarm.cancelAllRequests(); super.doOKAction(); if (!myRunFindActionOnClose) return; final SearchScope selectedScope = myScopeChooserCombo.getSelectedScope(); if (selectedScope == null) return; final FindSettings findSettings = FindSettings.getInstance(); findSettings.setDefaultScopeName(selectedScope.getDisplayName()); findSettings.setShowResultsInSeparateView(openInNewTab.isSelected()); try { filterOutUnusedVariableConstraints(myConfiguration); ConfigurationManager.getInstance(getProject()).addHistoryConfiguration(myConfiguration); startSearching(); } catch (MalformedPatternException ex) { reportMessage(SSRBundle.message("this.pattern.is.malformed.message", ex.getMessage()), searchCriteriaEdit); } } private void filterOutUnusedVariableConstraints(Configuration configuration) { final List<Variable> variables = getVariablesFromListeners(); final List<String> variableNames = new ArrayList<>(); for (Variable variable : variables) { variableNames.add(variable.getName()); } variableNames.add(Configuration.CONTEXT_VAR_NAME); configuration.getMatchOptions().retainVariableConstraints(variableNames); } public Configuration getConfiguration() { filterOutUnusedVariableConstraints(myConfiguration); setValuesToConfig(myConfiguration); return myConfiguration; } /** * Needs to be called on the event thread or while holding a read lock. */ protected boolean isValid() { try { Matcher.validate(searchContext.getProject(), getConfiguration().getMatchOptions()); } catch (MalformedPatternException ex) { reportMessage(SSRBundle.message("this.pattern.is.malformed.message", (ex.getMessage() != null) ? ex.getMessage() : ""), searchCriteriaEdit); return false; } catch (UnsupportedPatternException ex) { reportMessage(SSRBundle.message("this.pattern.is.unsupported.message", ex.getMessage()), searchCriteriaEdit); return false; } catch (NoMatchFoundException e) { reportMessage(e.getMessage(), searchCriteriaEdit); return false; } reportMessage("", null); return true; } protected void reportMessage(String message, Editor editor) { com.intellij.util.ui.UIUtil.invokeLaterIfNeeded(() -> { status.setText(message); status.setToolTipText(message); status.revalidate(); statusText.setLabelFor(editor != null ? editor.getContentComponent() : null); }); } protected void setValuesToConfig(Configuration config) { MatchOptions options = config.getMatchOptions(); if (myShowScopePanel) { boolean searchWithinHierarchy = IdeBundle.message("scope.class.hierarchy").equals(myScopeChooserCombo.getSelectedScopeName()); // We need to reset search within hierarchy scope during online validation since the scope works with user participation options.setScope( searchWithinHierarchy && !myDoingOkAction ? GlobalSearchScope.projectScope(getProject()) : myScopeChooserCombo.getSelectedScope()); } options.setRecursiveSearch(isRecursiveSearchEnabled() && recursiveMatching.isSelected()); ourFtSearchVariant = (FileType)fileTypes.getSelectedItem(); ourDialect = (Language)dialects.getSelectedItem(); ourContext = (String)contexts.getSelectedItem(); FileType fileType = ourFtSearchVariant; options.setFileType(fileType); options.setDialect(ourDialect); options.setPatternContext(ourContext); options.setSearchPattern(searchCriteriaEdit.getDocument().getText()); options.setCaseSensitiveMatch(caseSensitiveMatch.isSelected()); } @Override protected String getDimensionServiceKey() { return "#com.intellij.structuralsearch.plugin.ui.SearchDialog"; } @Override public void dispose() { disposeEditorContent(); myAlarm.cancelAllRequests(); super.dispose(); StructuralSearchPlugin.getInstance(getProject()).setDialogVisible(false); } protected void disposeEditorContent() { mySavedEditorText = searchCriteriaEdit.getDocument().getText(); // this will remove from myExcludedSet final PsiFile file = PsiDocumentManager.getInstance(searchContext.getProject()).getPsiFile(searchCriteriaEdit.getDocument()); if (file != null) { DaemonCodeAnalyzer.getInstance(searchContext.getProject()).setHighlightingEnabled(file, true); } EditorFactory.getInstance().releaseEditor(searchCriteriaEdit); } @Override protected String getHelpId() { return "find.structuredSearch"; } public SearchContext getSearchContext() { return searchContext; } }
package com.intellij.vcs.log.statistics; import com.intellij.internal.statistic.eventLog.FeatureUsageData; import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.vcs.log.ui.VcsLogInternalDataKeys; import org.jetbrains.annotations.NotNull; public class VcsLogUsageTriggerCollector { public static void triggerUsage(@NotNull AnActionEvent e, @NotNull Object action) { String name = action.getClass().getName(); if (name.contains(".")) name = name.substring(name.lastIndexOf(".") + 1); triggerUsage(e, name); } public static void triggerUsage(@NotNull AnActionEvent e, @NotNull String text) { triggerUsage(text, e.getData(VcsLogInternalDataKeys.FILE_HISTORY_UI) != null); } public static void triggerUsage(@NotNull String text) { triggerUsage(text, ""); } public static void triggerUsage(@NotNull String text, boolean isFromHistory) { triggerUsage(text, isFromHistory ? "history" : "log"); } private static void triggerUsage(@NotNull String text, @NotNull String context) { FUCounterUsageLogger.getInstance().logEvent("vcs.log.trigger", text, new FeatureUsageData().addData("context", context)); } }
package org.pocketcampus.plugin.food.android; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Vector; import org.pocketcampus.R; import org.pocketcampus.android.platform.sdk.core.PluginController; import org.pocketcampus.android.platform.sdk.core.PluginView; import org.pocketcampus.android.platform.sdk.ui.dialog.MenuDialog; import org.pocketcampus.android.platform.sdk.ui.dialog.RatingDialog; import org.pocketcampus.android.platform.sdk.ui.element.RatableView; import org.pocketcampus.android.platform.sdk.ui.element.TextViewElement; import org.pocketcampus.android.platform.sdk.ui.labeler.IRatableViewConstructor; import org.pocketcampus.android.platform.sdk.ui.labeler.IRatableViewLabeler; import org.pocketcampus.android.platform.sdk.ui.layout.StandardTitledLayout; import org.pocketcampus.android.platform.sdk.ui.list.RatableExpandableListViewElement; import org.pocketcampus.android.platform.sdk.ui.list.RatableListViewElement; import org.pocketcampus.plugin.food.android.iface.IFoodMainView; import org.pocketcampus.plugin.food.android.iface.IFoodModel; import org.pocketcampus.plugin.food.shared.Meal; import org.pocketcampus.plugin.food.shared.Sandwich; import org.pocketcampus.plugin.food.shared.SubmitStatus; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Toast; /** * The Main View of the Food plugin, first displayed when accessing Food. * * Displays menus by restaurants, preferences, suggestions and ratings, as well * as sandwiches * * @author Elodie (elodienilane.triponez@epfl.ch) * @author Oriane (oriane.rodriguez@epfl.ch) * */ public class FoodMainView extends PluginView implements IFoodMainView { /** Main Activity */ private Activity mActivity; /* MVC */ /** The controller that does the interface between model and view */ private FoodController mController; /** The corresponding model */ private IFoodModel mModel; /* Layout */ /** A simple full screen layout */ private StandardTitledLayout mLayout; /** The main list with menus and sandwiches */ private RatableExpandableListViewElement mList; /* Constants */ private final int SUGGESTIONS_REQUEST_CODE = 1; /* Listeners */ /** Listener for when you click on a line in the list */ private OnItemClickListener mOnLineClickListener; /** Listener for when you click on a rating in the list */ private OnItemClickListener mOnRatingClickListener; /** * Keeps in memory whether we are coming back from choosing restaurant * preferences */ private boolean backFromPreferences; /** * Defines what the main controller is for this view. */ @Override protected Class<? extends PluginController> getMainControllerClass() { return FoodController.class; } /** * Called once the view is connected to the controller. If you don't * implement <code>getMainControllerClass()</code> then the controller given * here will simply be <code>null</code>. */ @Override protected void onDisplay(Bundle savedInstanceState, PluginController controller) { Log.d("ACTIVITY", "onDisplay"); mActivity = this; // Get and cast the controller and model mController = (FoodController) controller; mModel = (FoodModel) controller.getModel(); // Ugly, but works for now backFromPreferences = false; // The StandardLayout is a RelativeLayout with a TextView in its center. mLayout = new StandardTitledLayout(this); mLayout.hideTitle(); // The ActionBar is added automatically when you call setContentView setContentView(mLayout); mList = new RatableExpandableListViewElement(this); // We need to force the display before asking the controller for the // data, // as the controller may take some time to get it. displayData(); } /** * Called when this view is accessed after already having been initialized * before */ @Override protected void onRestart() { super.onRestart(); Log.d("ACTIVITY", "onRestart"); if (backFromPreferences) { refreshDisplay(); } } /** * Initiates request for the restaurant, meal and sandwich data */ private void displayData() { mLayout.setText(getResources().getString(R.string.food_no_menus)); mController.getRestaurants(); mController.getMeals(); mController.getSandwiches(); } /** * Refreshes the display after some changes, e.g. preferences or suggestions */ private void refreshDisplay() { showMenusByRestaurants(); backFromPreferences = false; } /** * Main Food Options menu contains access to Meals by restaurants, ratings, * Sandwiches, Suggestions and Settings */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.food_main, menu); return true; } /** * Decides what happens when the options menu is opened and an option is * chosen (what view to display) */ @Override public boolean onOptionsItemSelected(android.view.MenuItem item) { if (item.getItemId() == R.id.food_by_resto) { showMenusByRestaurants(); } else if (item.getItemId() == R.id.food_by_sandwiches) { showSandwiches(); } else if (item.getItemId() == R.id.food_by_ratings) { showMenusByRatings(); } else if (item.getItemId() == R.id.food_by_suggestions) { // Extras to add to the Intent ArrayList<Meal> meals = (ArrayList<Meal>) mModel.getMeals(); // Intent to start the SuggestionsView Intent suggestions = new Intent(getApplicationContext(), FoodSuggestionsView.class); suggestions.putExtra("org.pocketcampus.suggestions.meals", meals); startActivityForResult(suggestions, SUGGESTIONS_REQUEST_CODE); } else if (item.getItemId() == R.id.food_by_settings) { backFromPreferences = true; Intent settings = new Intent(getApplicationContext(), FoodPreferencesView.class); startActivity(settings); } return true; } /** * Called when the list of restaurants has been updated */ public void restaurantsUpdated() { Log.d("RESTAURANT", "Restaurants updated"); } /** * Called when the list of menus has been updated Displays the view by * restaurants. */ @Override public void menusUpdated() { showMenusByRestaurants(); } /** * Creates a menu dialog for a particular meal * * @param meal */ public void menuDialog(Meal meal) { // Create the Builder for the Menu dialog MenuDialog.Builder b = new MenuDialog.Builder(mActivity); b.setCanceledOnTouchOutside(true); // Set different values for the dialog b.setTitle(meal.getRestaurant().getName() + " - " + meal.getName()); b.setDescription(meal.getMealDescription()); b.setRating((float) 0.0, meal.getRating().getNbVotes()); b.setFirstButton(R.string.food_menu_dialog_firstButton, new MenuDialogListener(b, meal)); b.setSecondButton(R.string.food_menu_dialog_secondButton, new MenuDialogListener(b, meal)); // b.setThirdButton(R.string.food_menu_dialog_thirdButton, // new MenuDialogListener(b, meal)); // Create the dialog and display it MenuDialog dialog = b.create(); dialog.show(); } /** * Called when the ratings have been updated Refreshes the view with the new * ratings */ @Override public void ratingsUpdated() { Log.d("RATING", "All Ratings updated"); mList.notifyDataSetChanged(); } /** * Creates a rating dialog for a particular meal * * @param meal */ public void ratingDialog(Meal meal, long rating) { // Create the Builder for the Rating dialog RatingDialog.Builder b = new RatingDialog.Builder(mActivity); // Set different values for the dialog b.setTitle(R.string.food_rating_dialog_title); b.setOkButton(R.string.food_rating_dialog_OK, new RatingDialogListener( b, meal, rating)); b.setCancelButton(R.string.food_rating_dialog_cancel, new RatingDialogListener()); // Create the dialog and display it RatingDialog dialog = b.create(); dialog.show(); } /** * Called after a vote has been cast by a user to check whether it was * successful * * @param status * what the server returned upon submitting the rating */ @Override public void ratingSubmitted(SubmitStatus status) { Log.d("RATING", "One Rating updated"); // Toast with the status if (status.equals(SubmitStatus.VALID)) { Log.d("RATING", "Valid"); Toast.makeText(this, R.string.food_rating_valid, Toast.LENGTH_SHORT) .show(); // Update the Ratings mController.getRatings(); } else if (status.equals(SubmitStatus.ALREADY_VOTED)) { Log.d("RATING", "Already Voted"); Toast.makeText(this, R.string.food_rating_already_voted, Toast.LENGTH_SHORT).show(); } else if (status.equals(SubmitStatus.TOOEARLY)) { Log.d("RATING", "Too Early"); Toast.makeText(this, R.string.food_rating_too_early, Toast.LENGTH_SHORT).show(); } else if (status.equals(SubmitStatus.ERROR)) { Log.d("RATING", "Error"); Toast.makeText(this, R.string.food_rating_error, Toast.LENGTH_SHORT) .show(); } } /** * Called when the sandwiches list is updated */ @Override public void sandwichesUpdated() { Log.d("SANDWICHES", "Sandwiches updated"); } /** * Displays a toast when an error happens upon contacting the server */ @Override public void networkErrorHappened() { Toast toast = Toast.makeText(getApplicationContext(), getString(R.string.food_network_error), Toast.LENGTH_SHORT); toast.show(); } /** * Updates the view with what has to be currently displayed */ public void updateView() { // mList.getAdapter().removeSections(); // switch (currentDisplayType_) { // case Restaurants: // showMenusByRestaurants(); // break; // case Ratings: // showMenusByRatings(); // break; // case Sandwiches: // showSandwiches(); // break; // case Suggestions: // showMenusBySuggestions(); // break; // ownerActivity_.refreshActionBar(currentDisplayType_); } /** * Sets the listeners for when you click on a view, when you are displaying * menus by restaurants. * * @param mealHashMap * the <code>HashMap</code> containing the daily menus */ public void setHashMapOnClickListeners( final HashMap<String, Vector<Meal>> mealHashMap) { // Create Listeners mOnLineClickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View v, int positionInSection, long arg3) { final Meal meal = mealHashMap.get(v.getTag()).get( positionInSection); menuDialog(meal); } }; mOnRatingClickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View okButton, int positionInSection, long rating) { final Meal meal = mealHashMap.get(okButton.getTag()).get( positionInSection); ratingDialog(meal, rating); } }; } /** * Set the listeners for when you click on a view, when you are displaying a * simple list of menus. * * @param mealList * the corresponding list of menus */ public void setListOnClickListeners(final List<Meal> mealList, RatableListViewElement l) { // Create Listeners mOnLineClickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View v, int position, long arg3) { final Meal meal = mealList.get(position); menuDialog(meal); } }; mOnRatingClickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View okButton, int position, long rating) { final Meal meal = mealList.get(position); ratingDialog(meal, rating); } }; l.setOnLineClickListener(mOnLineClickListener); l.setOnRatingClickListener(mOnRatingClickListener); } /** * Shows menus sorted by Restaurants */ public void showMenusByRestaurants() { final HashMap<String, Vector<Meal>> mealHashMap = mModel .getMealsByRestaurants(this); Log.d("MEALS", "Size of list of meals : " + mealHashMap.size()); if(mealHashMap != null) { /** * Iterate over the different restaurant menus */ mLayout.removeFillerView(); if (!mealHashMap.isEmpty()) { // Filtering restaurant that the user doesn't want to display mList = new RatableExpandableListViewElement(this, mealHashMap, mMealLabeler, mMealsViewConstructor); setHashMapOnClickListeners(mealHashMap); // Hide the text that says the list is empty mLayout.hideText(); // Set the title to Restaurants mLayout.setTitle(this.getString(R.string.food_by_restaurants)); // Add the list containing the meals mLayout.addFillerView(mList); } else { // Set the centered text to empty menus mLayout.setText(getString(R.string.food_no_menus)); // Hide the title as there is no content mLayout.hideTitle(); } } } /** * Shows menus sorted by Ratings */ public void showMenusByRatings() { List<Meal> mealsByRatings = mModel.getMealsByRatings(); Log.d("RATING", "Size of meals list : " + mealsByRatings.size()); if (mealsByRatings != null && !mealsByRatings.isEmpty()) { mLayout.removeFillerView(); // Create a new list by ratings RatableListViewElement l = new RatableListViewElement(this, mealsByRatings, mMealLabeler); setListOnClickListeners(mealsByRatings, l); // Hide the text that says the list is empty mLayout.hideText(); mLayout.setTitle(getString(R.string.food_by_ratings)); mLayout.addFillerView(l); } else { mLayout.setText(getString(R.string.food_no_menus)); mLayout.hideTitle(); } } /** * Shows menus sorted by Suggestions * * @param mealsBySuggestions * the list coming from the suggestions activity that has to be * displayed */ public void showMenusBySuggestions(ArrayList<Meal> mealsBySuggestions) { Log.d("RATING", "Size of meals by suggestions list : " + mealsBySuggestions.size()); if (mealsBySuggestions != null && !mealsBySuggestions.isEmpty()) { mLayout.removeFillerView(); RatableListViewElement l = new RatableListViewElement(this, mealsBySuggestions, mMealLabeler); setListOnClickListeners(mealsBySuggestions, l); // Hide the text that says the list is empty mLayout.hideText(); mLayout.setTitle(getString(R.string.food_by_suggestions)); mLayout.addFillerView(l); } else { mLayout.setText(getString(R.string.food_no_menus)); mLayout.hideTitle(); } } /** * Shows the list of Sandwiches by Restaurants */ public void showSandwiches() { final HashMap<String, Vector<Sandwich>> mSandwiches = mModel .getSandwiches(); Log.d("SANDWICHES", "Size of Sandwiches list : " + mSandwiches.size()); if(mSandwiches != null) { mLayout.removeFillerView(); mList = new RatableExpandableListViewElement(this, mSandwiches, mSandwichLabeler, mSandwichViewConstructor); if (!mSandwiches.isEmpty()) { mLayout.hideText(); mLayout.setTitle(this.getString(R.string.food_by_sandwiches)); mLayout.addFillerView(mList); } else { mLayout.setText(getString(R.string.food_no_sandwiches)); mLayout.hideTitle(); } } } /** * Called when one of the Menu Dialog buttons is clicked. * */ private class MenuDialogListener implements DialogInterface.OnClickListener { private MenuDialog.Builder builder; private Meal meal; private float rating; public MenuDialogListener(MenuDialog.Builder b, Meal m) { builder = b; meal = m; } @Override public void onClick(DialogInterface dialog, int code) { switch (code) { case DialogInterface.BUTTON1: rating = builder.getSubmittedRating(); Log.d("RATING", "Rating submitted : " + rating); dialog.dismiss(); mController.setRating((float) rating, meal); break; case DialogInterface.BUTTON2: // Pictures // Log.d("PICTURES", "Picture taken"); dialog.dismiss(); break; case DialogInterface.BUTTON3: // Go there Log.d("MAP", "Go there clicked"); dialog.dismiss(); break; default: break; } } } /** * Called when one of the Rating Dialog buttons is clicked. * */ private class RatingDialogListener implements DialogInterface.OnClickListener { private RatingDialog.Builder builder; private Meal meal; private float rating; public RatingDialogListener() { } public RatingDialogListener(RatingDialog.Builder b, Meal m, float r) { builder = b; meal = m; rating = r; } @Override public void onClick(DialogInterface dialog, int code) { switch (code) { case DialogInterface.BUTTON_POSITIVE: rating = builder.getSubmittedRating(); Log.d("RATING", "Rating submitted : " + rating); dialog.dismiss(); mController.setRating((float) rating, meal); break; case DialogInterface.BUTTON_NEGATIVE: dialog.dismiss(); break; default: break; } } } /** * Called when coming back from another activity that was called with an * intent and from which we are expecting a result * * @param requestCode * what request this result corresponds to * @param resultCode * the status of the result * @param data * the information gotten from the activity */ public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case SUGGESTIONS_REQUEST_CODE: // Result from the Suggestions class Log.d("SUGGESTIONS", "OnActivityResult"); if (resultCode == Activity.RESULT_OK) { Bundle extras = data.getExtras(); if (extras != null) { @SuppressWarnings("unchecked") ArrayList<Meal> list = (ArrayList<Meal>) extras .getSerializable("org.pocketcampus.suggestions.meals"); Log.d("SUGGESTIONS", "Meals in return : " + list.size()); showMenusBySuggestions(list); } else { Log.d("SUGGESTIONS", "No extras !"); } } else { Log.d("SUGGESTIONS", "RESULT_PAS_OK !"); } break; } } /** * The labeler for a meal, to tell how it has to be displayed in a generic * view. */ IRatableViewLabeler<Meal> mMealLabeler = new IRatableViewLabeler<Meal>() { /** * Returns the title of a meal * * @param meal * the meal to be displayed * @return */ @Override public String getTitle(Meal meal) { return meal.getName(); } /** * Returns the description of a meal * * @param meal * the meal to be displayed * @return */ @Override public String getDescription(Meal meal) { return meal.getMealDescription(); } /** * Returns the Rating of a meal * * @param meal * the meal to be displayed * @return */ @Override public float getRating(Meal meal) { return (float) meal.getRating().getRatingValue(); } /** * Returns the Number Of Votes for a meal * * @param meal * the meal to be displayed * @return */ @Override public int getNbVotes(Meal meal) { return meal.getRating().getNbVotes(); } /** * Returns the name of the Restaurant the meal is available at. * * @param meal * the meal to be displayed * @return */ @Override public String getPlaceName(Meal meal) { return meal.getRestaurant().getName(); } }; /** * The labeler for a Sandwich, to tell how it has to be displayed in a * generic view. */ IRatableViewLabeler<Sandwich> mSandwichLabeler = new IRatableViewLabeler<Sandwich>() { @Override public String getTitle(Sandwich sandwich) { return sandwich.getName(); } @Override public String getDescription(Sandwich sandwich) { return ""; } @Override public float getRating(Sandwich sandwich) { return (float) 0; } @Override public int getNbVotes(Sandwich sandwich) { return 0; } @Override public String getPlaceName(Sandwich sandwich) { return sandwich.getRestaurant().getName(); } }; /** * The constructor for a Meal View to be displayed in the list */ IRatableViewConstructor mMealsViewConstructor = new IRatableViewConstructor() { @Override public View getNewView(Object currentObject, Context context, IRatableViewLabeler<? extends Object> labeler, int position) { return new RatableView(currentObject, context, labeler, mOnLineClickListener, mOnRatingClickListener, position); } }; /** * The constructor for a Sandwich View to be displayed in the list */ IRatableViewConstructor mSandwichViewConstructor = new IRatableViewConstructor() { @Override public View getNewView(Object currentObject, Context context, IRatableViewLabeler<? extends Object> labeler, int position) { return new TextViewElement(currentObject, context, labeler, null, null, position); } }; }
package org.jenkins.tools.test.servlets.util; import org.jenkins.tools.test.model.MavenCoordinates; import org.jenkins.tools.test.model.PluginCompatReport; import org.jenkins.tools.test.model.PluginCompatResult; import org.jenkins.tools.test.model.PluginInfos; import java.util.*; /** * @author fcamblor */ public class JsonUtil { public static String toJson(PluginCompatReport report){ return String.format("{\"coreCoordinates\":%s,\"plugins\":%s,\"results\":%s}", toJson(report.getTestedCoreCoordinates()), toJson(report.getPluginCompatTests().keySet()), toJson(report.getPluginCompatTests())); } public static String toJson(Map<PluginInfos, List<PluginCompatResult>> pluginCompatTests) { StringBuilder sb = new StringBuilder("["); for(PluginInfos pi : pluginCompatTests.keySet()){ sb.append(String.format("{\"plugin\":\"%s:%s\",\"results\":%s},", pi.pluginName, pi.pluginVersion, toJson(pluginCompatTests.get(pi)))); } if(pluginCompatTests.keySet().size()!=0){ sb.deleteCharAt(sb.length()-1); // Removing last comma } sb.append("]"); return sb.toString(); } public static String toJson(List<PluginCompatResult> pluginCompatResults) { // Ensuring results are sorted Collections.sort(pluginCompatResults); StringBuilder sb = new StringBuilder("["); for(PluginCompatResult res : pluginCompatResults){ sb.append(String.format("{\"core\":\"%s\",\"status\":\"%s\",\"date\":%s,%s%s%s%s},",res.coreCoordinates.toGAV(),res.status.name(), res.compatTestExecutedOn.getTime(), displayMessage("err", res.errorMessage), res.errorMessage==null?"":",", displayMessages("warn", res.warningMessages), res.warningMessages==null?"":",")); } if(pluginCompatResults.size()!=0){ sb.deleteCharAt(sb.length()-1); // Removing last comma } sb.append("]"); return sb.toString(); } public static String displayMessages(String label, Collection<String> messages) { if(messages==null){ return ""; } StringBuilder sb = new StringBuilder(String.format("\"%s\":[", label)); for(String msg : messages){ sb.append(String.format("%s,",displayMessage(null, msg))); } if(messages.size()!=0){ sb.deleteCharAt(sb.length()-1); // Removing last comma } sb.append("]"); return sb.toString(); } public static String displayMessage(String label, String errorMessage) { if(errorMessage == null){ return ""; } return String.format("%s\"%s\"", label==null?"":"\""+label+"\":", errorMessage.replaceAll("\"", "\\\\\"").replaceAll("\r", "\\\\r").replaceAll("\n", "\\\\n")); } public static String toJson(Set<PluginInfos> pluginInfos) { StringBuilder sb = new StringBuilder("["); for(PluginInfos pi : pluginInfos){ sb.append(String.format("{\"name\":\"%s\",\"version\":\"%s\",\"url\":\"%s\"},", pi.pluginName, pi.pluginVersion, pi.pluginUrl)); } if(pluginInfos.size()!=0){ sb.deleteCharAt(sb.length()-1); // Removing last comma } sb.append("]"); return sb.toString(); } public static String toJson(SortedSet<MavenCoordinates> testedCoreCoordinates) { StringBuilder sb = new StringBuilder("["); for(MavenCoordinates coord : testedCoreCoordinates){ sb.append(String.format("{\"g\":\"%s\",\"a\":\"%s\",\"v\":\"%s\"},", coord.groupId, coord.artifactId, coord.version)); } if(testedCoreCoordinates.size()!=0){ sb.deleteCharAt(sb.length()-1); // Removing last comma } sb.append("]"); return sb.toString(); } }
package org.jkiss.dbeaver.ext.db2.model.cache; import java.sql.ResultSet; import java.sql.SQLException; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.ext.db2.model.DB2Alias; import org.jkiss.dbeaver.ext.db2.model.DB2Schema; import org.jkiss.dbeaver.model.exec.jdbc.JDBCExecutionContext; import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement; import org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement; import org.jkiss.dbeaver.model.impl.jdbc.cache.JDBCObjectCache; /** * * Cache for DB2 Aliases * * @author Denis Forveille * */ public final class DB2AliasCache extends JDBCObjectCache<DB2Schema, DB2Alias> { private static String SQL_ALL; static { StringBuilder sb = new StringBuilder(1024); sb.append(" SELECT 'TABLE' as TYPE "); sb.append(" , TABNAME AS NAME"); sb.append(" , BASE_TABSCHEMA AS BASE_SCHEMA"); sb.append(" , BASE_TABNAME AS BASE_NAME"); sb.append(" FROM SYSCAT.TABLES"); sb.append(" WHERE TABSCHEMA = ?"); sb.append(" AND TYPE = 'A'"); sb.append(" UNION ALL"); sb.append(" SELECT 'SEQUENCE' as TYPE "); sb.append(" , SEQNAME AS NAME"); sb.append(" , BASE_SEQSCHEMA AS BASE_SCHEMA"); sb.append(" , BASE_SEQNAME AS BASE_NAME"); sb.append(" FROM SYSCAT.SEQUENCES "); sb.append(" WHERE SEQSCHEMA = ?"); sb.append(" AND SEQTYPE = 'A'"); sb.append(" UNION ALL"); sb.append(" SELECT 'MODULE' as TYPE "); sb.append(" , MODULENAME AS NAME"); sb.append(" , BASE_MODULESCHEMA AS BASE_SCHEMA"); sb.append(" , BASE_MODULENAME AS BASE_NAME"); sb.append(" FROM SYSCAT.MODULES "); sb.append(" WHERE MODULESCHEMA = ?"); sb.append(" AND MODULETYPE = 'A'"); sb.append(" ORDER BY NAME"); sb.append(" , TYPE"); sb.append(" WITH UR"); SQL_ALL = sb.toString(); } @Override protected JDBCStatement prepareObjectsStatement(JDBCExecutionContext context, DB2Schema db2Schema) throws SQLException { final JDBCPreparedStatement dbStat = context.prepareStatement(SQL_ALL); dbStat.setString(1, db2Schema.getName()); dbStat.setString(2, db2Schema.getName()); dbStat.setString(3, db2Schema.getName()); return dbStat; } protected DB2Alias fetchObject(JDBCExecutionContext context, DB2Schema db2Schema, ResultSet resultSet) throws SQLException, DBException { return new DB2Alias(context.getProgressMonitor(), db2Schema, resultSet); } }
package com.intellij.structuralsearch.impl.matcher; import com.intellij.psi.*; import org.jetbrains.annotations.NonNls; public class MatchUtils { public static final String SPECIAL_CHARS = "*(){}[]^$\\.-|"; public static final boolean compareWithNoDifferenceToPackage(final String typeImage,@NonNls final String typeImage2) { if (typeImage == null || typeImage2 == null) return typeImage == typeImage2; return typeImage2.endsWith(typeImage) && ( typeImage.length() == typeImage2.length() || typeImage2.charAt(typeImage2.length()-typeImage.length()-1)=='.' // package separator ); } public static PsiElement getReferencedElement(final PsiElement element) { if (element instanceof PsiReference) { return ((PsiReference)element).resolve(); } if (element instanceof PsiTypeElement) { PsiType type = ((PsiTypeElement)element).getType(); if (type instanceof PsiArrayType) { type = ((PsiArrayType)type).getComponentType(); } if (type instanceof PsiClassType) { return ((PsiClassType)type).resolve(); } return null; } return element; } }
package com.intellij.structuralsearch.plugin.ui; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiNameIdentifierOwner; import com.intellij.structuralsearch.MatchResult; import com.intellij.structuralsearch.MatchResultSink; import com.intellij.structuralsearch.MatchingProcess; import com.intellij.structuralsearch.SSRBundle; import com.intellij.structuralsearch.impl.matcher.MatchResultImpl; import com.intellij.structuralsearch.plugin.StructuralSearchPlugin; import com.intellij.structuralsearch.plugin.ui.actions.DoSearchAction; import com.intellij.usageView.UsageInfo; import com.intellij.usages.Usage; import com.intellij.usages.UsageInfo2UsageAdapter; import com.intellij.util.ObjectUtils; import com.intellij.util.Processor; public class SearchCommand { protected UsageViewContext context; private MatchingProcess process; protected Project project; public SearchCommand(Project _project, UsageViewContext _context) { project = _project; context = _context; } public void findUsages(final Processor<Usage> processor) { final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); DoSearchAction.execute( project, new MatchResultSink() { int count; public void setMatchingProcess(MatchingProcess _process) { process = _process; findStarted(); } public void processFile(PsiFile element) { final VirtualFile virtualFile = element.getVirtualFile(); if (virtualFile!=null) progress.setText( SSRBundle.message("looking.in.progress.message",virtualFile.getPresentableName()) ); } public void matchingFinished() { findEnded(); progress.setText( SSRBundle.message("found.progress.message", count ) ); } public ProgressIndicator getProgressIndicator() { return progress; } public void newMatch(MatchResult result) { UsageInfo info; if (MatchResult.MULTI_LINE_MATCH.equals(result.getName())) { int start = -1; int end = -1; PsiElement parent = result.getMatchRef().getElement().getParent(); for (final MatchResult matchResult : ((MatchResultImpl)result).getMatches()) { PsiElement el = matchResult.getMatchRef().getElement(); final int elementStart = el.getTextRange().getStartOffset(); if (start == -1 || start > elementStart) { start = elementStart; } final int newend = elementStart + el.getTextLength(); if (newend > end) { end = newend; } } final int parentStart = parent.getTextRange().getStartOffset(); int startOffset = start - parentStart; info = new UsageInfo(parent,startOffset,end - parentStart); } else { PsiElement element = result.getMatch(); if (element instanceof PsiNameIdentifierOwner) { element = ObjectUtils.notNull(((PsiNameIdentifierOwner)element).getNameIdentifier(), element); } info = new UsageInfo(element, result.getStart(), result.getEnd() == -1 ? element.getTextLength() : result.getEnd()); } Usage usage = new UsageInfo2UsageAdapter(info); processor.process(usage); foundUsage(result, usage); ++count; } }, context.getConfiguration() ); } public void stopAsyncSearch() { if (process!=null) process.stop(); } protected void findStarted() { StructuralSearchPlugin.getInstance(project).setSearchInProgress(true); } protected void findEnded() { StructuralSearchPlugin.getInstance(project).setSearchInProgress(false); } protected void foundUsage(MatchResult result, Usage usage) { } }
package com.charlesmadere.hummingbird.adapters; import android.content.Context; import android.support.annotation.Nullable; import com.charlesmadere.hummingbird.R; import com.charlesmadere.hummingbird.models.Feed; import com.charlesmadere.hummingbird.models.FollowedStory; import com.charlesmadere.hummingbird.models.FollowedSubstory; import com.charlesmadere.hummingbird.views.FollowedSubstoryStandaloneItemView; import com.charlesmadere.hummingbird.views.ReplySubstoryStandaloneItemView; import java.util.ArrayList; import java.util.HashMap; public class FollowedStoryAdapter extends BaseMultiPaginationAdapter { public FollowedStoryAdapter(final Context context) { super(context); } @Override protected HashMap<Class, Integer> getItemViewKeyMap() { final HashMap<Class, Integer> map = new HashMap<>(3); map.put(FollowedStory.class, R.layout.item_followed_story_standalone); map.put(FollowedSubstory.class, R.layout.item_followed_substory_standalone); map.put(String.class, R.layout.item_charsequence_plain); return map; } @Override public void onBindViewHolder(final AdapterView.ViewHolder holder, final int position) { if (holder.getAdapterView() instanceof ReplySubstoryStandaloneItemView) { final boolean showDivider = isPaginating() ? position + 2 < getItemCount() : position + 1 < getItemCount(); ((FollowedSubstoryStandaloneItemView) holder.getAdapterView()).setContent( (FollowedSubstory) getItem(position), showDivider); } else { super.onBindViewHolder(holder, position); } } public void set(final FollowedStory followedStory, @Nullable final Feed feed) { final ArrayList<Object> list = new ArrayList<>(); list.add(followedStory); if (feed == null || !feed.hasSubstories()) { list.add(getContext().getString(R.string.nothing_more_to_show)); } else { list.addAll(feed.getSubstories()); } super.set(list); } }
package org.rabix.engine.processor.handler.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.rabix.bindings.BindingException; import org.rabix.bindings.model.Job; import org.rabix.bindings.model.Job.JobStatus; import org.rabix.bindings.model.dag.DAGLinkPort.LinkPortType; import org.rabix.common.helper.CloneHelper; import org.rabix.common.helper.InternalSchemaHelper; import org.rabix.engine.JobHelper; import org.rabix.engine.db.AppDB; import org.rabix.engine.db.DAGNodeDB; import org.rabix.engine.event.Event; import org.rabix.engine.event.impl.InputUpdateEvent; import org.rabix.engine.event.impl.JobStatusEvent; import org.rabix.engine.event.impl.OutputUpdateEvent; import org.rabix.engine.model.JobRecord; import org.rabix.engine.model.JobStatsRecord; import org.rabix.engine.model.LinkRecord; import org.rabix.engine.model.VariableRecord; import org.rabix.engine.model.scatter.ScatterStrategy; import org.rabix.engine.processor.EventProcessor; import org.rabix.engine.processor.handler.EventHandler; import org.rabix.engine.processor.handler.EventHandlerException; import org.rabix.engine.service.ContextRecordService; import org.rabix.engine.service.JobRecordService; import org.rabix.engine.service.JobService; import org.rabix.engine.service.JobStatsRecordService; import org.rabix.engine.service.LinkRecordService; import org.rabix.engine.service.VariableRecordService; import org.rabix.engine.service.impl.JobRecordServiceImpl.JobState; import com.google.inject.Inject; /** * Handles {@link OutputUpdateEvent} events. */ public class OutputEventHandler implements EventHandler<OutputUpdateEvent> { private JobRecordService jobRecordService; private LinkRecordService linkService; private VariableRecordService variableService; private ContextRecordService contextService; private JobStatsRecordService jobStatsRecordService; private final EventProcessor eventProcessor; private DAGNodeDB dagNodeDB; private AppDB appDB; private JobService jobService; @Inject public OutputEventHandler(EventProcessor eventProcessor, JobRecordService jobRecordService, VariableRecordService variableService, LinkRecordService linkService, ContextRecordService contextService, DAGNodeDB dagNodeDB, AppDB appDB, JobService jobService, JobStatsRecordService jobStatsRecordService) { this.dagNodeDB = dagNodeDB; this.appDB = appDB; this.jobRecordService = jobRecordService; this.linkService = linkService; this.contextService = contextService; this.variableService = variableService; this.eventProcessor = eventProcessor; this.jobService = jobService; this.jobStatsRecordService = jobStatsRecordService; } public void handle(final OutputUpdateEvent event) throws EventHandlerException { JobRecord sourceJob = jobRecordService.find(event.getJobId(), event.getContextId()); if (sourceJob.getState().equals(JobState.COMPLETED)) { return; } if (event.isFromScatter()) { jobRecordService.resetOutputPortCounter(sourceJob, event.getNumberOfScattered(), event.getPortId()); } VariableRecord sourceVariable = variableService.find(event.getJobId(), event.getPortId(), LinkPortType.OUTPUT, event.getContextId()); jobRecordService.decrementPortCounter(sourceJob, event.getPortId(), LinkPortType.OUTPUT); variableService.addValue(sourceVariable, event.getValue(), event.getPosition(), sourceJob.isScatterWrapper() || event.isFromScatter()); variableService.update(sourceVariable); // TODO wha? jobRecordService.update(sourceJob); if (sourceJob.isCompleted()) { if(sourceJob.getOutputCounter(sourceVariable.getPortId()) != null) { if ((sourceJob.isContainer() || sourceJob.isScatterWrapper()) && sourceJob.getParentId() != null && sourceJob.getParentId().equals(sourceJob.getRootId())) { JobStatsRecord jobStatsRecord = jobStatsRecordService.findOrCreate(sourceJob.getRootId()); jobStatsRecord.increaseCompleted(); jobStatsRecord.increaseRunning(); jobStatsRecordService.update(jobStatsRecord); } if (sourceJob.isRoot()) { Map<String, Object> outputs = new HashMap<>(); List<VariableRecord> outputVariables = variableService.find(sourceJob.getId(), LinkPortType.OUTPUT, sourceJob.getRootId()); for (VariableRecord outputVariable : outputVariables) { Object value = CloneHelper.deepCopy(variableService.getValue(outputVariable)); outputs.put(outputVariable.getPortId(), value); } Job rootJob = createRootJob(sourceJob, JobHelper.transformStatus(sourceJob.getState())); jobService.handleJobRootPartiallyCompleted(rootJob, event.getProducedByNode()); if(sourceJob.isRoot() && sourceJob.isContainer()) { // if root job is CommandLineTool OutputUpdateEvents are created from JobStatusEvent eventProcessor.send(new JobStatusEvent(sourceJob.getId(), event.getContextId(), JobState.COMPLETED, outputs, event.getEventGroupId(), event.getProducedByNode())); jobService.handleJobCompleted(rootJob); } return; } else { try { Job completedJob = JobHelper.createCompletedJob(sourceJob, JobStatus.COMPLETED, jobRecordService, variableService, linkService, contextService, dagNodeDB, appDB); jobService.handleJobCompleted(completedJob); } catch (BindingException e) { } } } } if (sourceJob.isRoot()) { jobService.handleJobRootPartiallyCompleted(createRootJob(sourceJob, JobHelper.transformStatus(sourceJob.getState())), event.getProducedByNode()); } Object value = null; if (sourceJob.isScatterWrapper()) { ScatterStrategy scatterStrategy = sourceJob.getScatterStrategy(); boolean isValueFromScatterStrategy = false; if (scatterStrategy.isBlocking()) { if (sourceJob.isOutputPortReady(event.getPortId())) { isValueFromScatterStrategy = true; value = scatterStrategy.values(variableService, sourceJob.getId(), event.getPortId(), event.getContextId()); } else { return; } } List<LinkRecord> links = linkService.findBySourceAndSourceType(sourceVariable.getJobId(), sourceVariable.getPortId(), LinkPortType.OUTPUT, event.getContextId()); for (LinkRecord link : links) { if (!isValueFromScatterStrategy) { value = null; // reset } VariableRecord destinationVariable = variableService.find(link.getDestinationJobId(), link.getDestinationJobPort(), link.getDestinationVarType(), event.getContextId()); JobRecord destinationJob = null; boolean isDestinationPortScatterable = false; switch (destinationVariable.getType()) { case INPUT: destinationJob = jobRecordService.find(destinationVariable.getJobId(), destinationVariable.getRootId()); isDestinationPortScatterable = destinationJob.isScatterPort(destinationVariable.getPortId()); if (isDestinationPortScatterable && !destinationJob.isBlocking() && !(destinationJob.getInputPortIncoming(event.getPortId()) > 1)) { value = value != null ? value : event.getValue(); int numberOfScattered = sourceJob.getNumberOfGlobalOutputs(); Event updateInputEvent = new InputUpdateEvent(event.getContextId(), destinationVariable.getJobId(), destinationVariable.getPortId(), value, true, numberOfScattered, event.getPosition(), event.getEventGroupId(), event.getProducedByNode()); eventProcessor.send(updateInputEvent); } else { if (sourceJob.isOutputPortReady(event.getPortId())) { value = value != null ? value : variableService.getValue(sourceVariable); Event updateInputEvent = new InputUpdateEvent(event.getContextId(), destinationVariable.getJobId(), destinationVariable.getPortId(), value, link.getPosition(), event.getEventGroupId(), event.getProducedByNode()); eventProcessor.send(updateInputEvent); } } break; case OUTPUT: destinationJob = jobRecordService.find(destinationVariable.getJobId(), destinationVariable.getRootId()); if (destinationJob.getOutputPortIncoming(event.getPortId()) > 1) { if (sourceJob.isOutputPortReady(event.getPortId())) { value = value != null ? value : variableService.getValue(sourceVariable); Event updateInputEvent = new OutputUpdateEvent(event.getContextId(), destinationVariable.getJobId(), destinationVariable.getPortId(), value, link.getPosition(), event.getEventGroupId(), event.getProducedByNode()); eventProcessor.send(updateInputEvent); } } else { value = value != null ? value : event.getValue(); if (isValueFromScatterStrategy) { Event updateOutputEvent = new OutputUpdateEvent(event.getContextId(), destinationVariable.getJobId(), destinationVariable.getPortId(), value, false, 1, 1, event.getEventGroupId(), event.getProducedByNode()); eventProcessor.send(updateOutputEvent); } else { int numberOfScattered = sourceJob.getNumberOfGlobalOutputs(); Event updateOutputEvent = new OutputUpdateEvent(event.getContextId(), destinationVariable.getJobId(), destinationVariable.getPortId(), value, true, numberOfScattered, event.getPosition(), event.getEventGroupId(), event.getProducedByNode()); eventProcessor.send(updateOutputEvent); } } break; } } return; } if (sourceJob.isOutputPortReady(event.getPortId())) { List<LinkRecord> links = linkService.findBySourceAndSourceType(event.getJobId(), event.getPortId(), LinkPortType.OUTPUT, event.getContextId()); for (LinkRecord link : links) { VariableRecord destinationVariable = variableService.find(link.getDestinationJobId(), link.getDestinationJobPort(), link.getDestinationVarType(), event.getContextId()); value = variableService.getValue(sourceVariable); switch (destinationVariable.getType()) { case INPUT: Event updateInputEvent = new InputUpdateEvent(event.getContextId(), destinationVariable.getJobId(), destinationVariable.getPortId(), value, link.getPosition(), event.getEventGroupId(), event.getProducedByNode()); eventProcessor.send(updateInputEvent); break; case OUTPUT: if (sourceJob.isScattered()) { int numberOfScattered = sourceJob.getNumberOfGlobalOutputs(); int position = InternalSchemaHelper.getScatteredNumber(sourceJob.getId()); Event updateOutputEvent = new OutputUpdateEvent(event.getContextId(), destinationVariable.getJobId(), destinationVariable.getPortId(), value, true, numberOfScattered, position, event.getEventGroupId(), event.getProducedByNode()); eventProcessor.send(updateOutputEvent); } else if (InternalSchemaHelper.getParentId(sourceJob.getId()).equals(destinationVariable.getJobId())) { Event updateOutputEvent = new OutputUpdateEvent(event.getContextId(), destinationVariable.getJobId(), destinationVariable.getPortId(), value, link.getPosition(), event.getEventGroupId(), event.getProducedByNode()); eventProcessor.send(updateOutputEvent); } break; } } } } private Job createRootJob(JobRecord jobRecord, JobStatus status) { Map<String, Object> outputs = new HashMap<>(); List<VariableRecord> outputVariables = variableService.find(jobRecord.getId(), LinkPortType.OUTPUT, jobRecord.getRootId()); for (VariableRecord outputVariable : outputVariables) { Object value = CloneHelper.deepCopy(variableService.getValue(outputVariable)); outputs.put(outputVariable.getPortId(), value); } return JobHelper.createRootJob(jobRecord, status, jobRecordService, variableService, linkService, contextService, dagNodeDB, appDB, outputs); } }
package net.runelite.client.plugins.cluescrolls.clues; import com.google.common.collect.ImmutableSet; import java.awt.Color; import java.awt.Graphics2D; import java.util.Set; import lombok.Getter; import net.runelite.api.EquipmentInventorySlot; import static net.runelite.api.EquipmentInventorySlot.AMULET; import static net.runelite.api.EquipmentInventorySlot.BODY; import static net.runelite.api.EquipmentInventorySlot.BOOTS; import static net.runelite.api.EquipmentInventorySlot.CAPE; import static net.runelite.api.EquipmentInventorySlot.GLOVES; import static net.runelite.api.EquipmentInventorySlot.HEAD; import static net.runelite.api.EquipmentInventorySlot.LEGS; import static net.runelite.api.EquipmentInventorySlot.RING; import static net.runelite.api.EquipmentInventorySlot.SHIELD; import static net.runelite.api.EquipmentInventorySlot.WEAPON; import net.runelite.api.Item; import static net.runelite.api.ItemID.ABYSSAL_WHIP; import static net.runelite.api.ItemID.ADAMANT_2H_SWORD; import static net.runelite.api.ItemID.ADAMANT_BOOTS; import static net.runelite.api.ItemID.ADAMANT_DAGGER; import static net.runelite.api.ItemID.ADAMANT_FULL_HELM; import static net.runelite.api.ItemID.ADAMANT_HALBERD; import static net.runelite.api.ItemID.ADAMANT_MED_HELM; import static net.runelite.api.ItemID.ADAMANT_PLATEBODY; import static net.runelite.api.ItemID.ADAMANT_PLATELEGS; import static net.runelite.api.ItemID.ADAMANT_PLATESKIRT; import static net.runelite.api.ItemID.ADAMANT_SQ_SHIELD; import static net.runelite.api.ItemID.ADAMANT_SWORD; import static net.runelite.api.ItemID.AHRIMS_HOOD_0; import static net.runelite.api.ItemID.AHRIMS_HOOD_100; import static net.runelite.api.ItemID.AHRIMS_ROBESKIRT_0; import static net.runelite.api.ItemID.AHRIMS_ROBESKIRT_100; import static net.runelite.api.ItemID.AHRIMS_ROBETOP_0; import static net.runelite.api.ItemID.AHRIMS_ROBETOP_100; import static net.runelite.api.ItemID.AHRIMS_STAFF_0; import static net.runelite.api.ItemID.AHRIMS_STAFF_100; import static net.runelite.api.ItemID.AIR_TIARA; import static net.runelite.api.ItemID.AMULET_OF_GLORY; import static net.runelite.api.ItemID.AMULET_OF_GLORY1; import static net.runelite.api.ItemID.AMULET_OF_GLORY2; import static net.runelite.api.ItemID.AMULET_OF_GLORY3; import static net.runelite.api.ItemID.AMULET_OF_GLORY4; import static net.runelite.api.ItemID.AMULET_OF_GLORY5; import static net.runelite.api.ItemID.AMULET_OF_GLORY6; import static net.runelite.api.ItemID.AMULET_OF_POWER; import static net.runelite.api.ItemID.AMULET_OF_STRENGTH; import static net.runelite.api.ItemID.AMULET_OF_THE_DAMNED; import static net.runelite.api.ItemID.ANCIENT_CROZIER; import static net.runelite.api.ItemID.ANCIENT_MITRE; import static net.runelite.api.ItemID.ANCIENT_STOLE; import static net.runelite.api.ItemID.ARCLIGHT; import static net.runelite.api.ItemID.ARMADYL_CROZIER; import static net.runelite.api.ItemID.ARMADYL_MITRE; import static net.runelite.api.ItemID.ARMADYL_STOLE; import static net.runelite.api.ItemID.BANDOS_BOOTS; import static net.runelite.api.ItemID.BANDOS_CLOAK; import static net.runelite.api.ItemID.BANDOS_CROZIER; import static net.runelite.api.ItemID.BANDOS_GODSWORD; import static net.runelite.api.ItemID.BANDOS_MITRE; import static net.runelite.api.ItemID.BANDOS_PLATEBODY; import static net.runelite.api.ItemID.BANDOS_STOLE; import static net.runelite.api.ItemID.BARROWS_GLOVES; import static net.runelite.api.ItemID.BLACK_AXE; import static net.runelite.api.ItemID.BLACK_BOATER; import static net.runelite.api.ItemID.BLACK_CAPE; import static net.runelite.api.ItemID.BLACK_DHIDE_BODY; import static net.runelite.api.ItemID.BLACK_DHIDE_CHAPS; import static net.runelite.api.ItemID.BLACK_DHIDE_VAMB; import static net.runelite.api.ItemID.BLACK_DRAGON_MASK; import static net.runelite.api.ItemID.BLACK_PLATEBODY; import static net.runelite.api.ItemID.BLACK_SALAMANDER; import static net.runelite.api.ItemID.BLACK_SLAYER_HELMET; import static net.runelite.api.ItemID.BLACK_SLAYER_HELMET_I; import static net.runelite.api.ItemID.BLUE_BOATER; import static net.runelite.api.ItemID.BLUE_BOOTS; import static net.runelite.api.ItemID.BLUE_DHIDE_BODY; import static net.runelite.api.ItemID.BLUE_DHIDE_CHAPS; import static net.runelite.api.ItemID.BLUE_DHIDE_VAMB; import static net.runelite.api.ItemID.BLUE_ROBE_TOP; import static net.runelite.api.ItemID.BLUE_WIZARD_HAT; import static net.runelite.api.ItemID.BLUE_WIZARD_ROBE; import static net.runelite.api.ItemID.BOBS_PURPLE_SHIRT; import static net.runelite.api.ItemID.BOBS_RED_SHIRT; import static net.runelite.api.ItemID.BODY_TIARA; import static net.runelite.api.ItemID.BONE_DAGGER; import static net.runelite.api.ItemID.BONE_SPEAR; import static net.runelite.api.ItemID.BOOK_OF_BALANCE; import static net.runelite.api.ItemID.BOOK_OF_DARKNESS; import static net.runelite.api.ItemID.BOOK_OF_LAW; import static net.runelite.api.ItemID.BOOK_OF_WAR; import static net.runelite.api.ItemID.BRINE_SABRE; import static net.runelite.api.ItemID.BRONZE_2H_SWORD; import static net.runelite.api.ItemID.BRONZE_AXE; import static net.runelite.api.ItemID.BRONZE_CHAINBODY; import static net.runelite.api.ItemID.BRONZE_DAGGER; import static net.runelite.api.ItemID.BRONZE_FULL_HELM; import static net.runelite.api.ItemID.BRONZE_PLATELEGS; import static net.runelite.api.ItemID.BRONZE_SPEAR; import static net.runelite.api.ItemID.BRONZE_SQ_SHIELD; import static net.runelite.api.ItemID.BROWN_APRON; import static net.runelite.api.ItemID.BROWN_HEADBAND; import static net.runelite.api.ItemID.BRUISE_BLUE_SNELM_3343; import static net.runelite.api.ItemID.CAPE_OF_LEGENDS; import static net.runelite.api.ItemID.CASTLE_WARS_BRACELET3; import static net.runelite.api.ItemID.CASTLE_WARS_BRACELET1; import static net.runelite.api.ItemID.CLIMBING_BOOTS; import static net.runelite.api.ItemID.COIF; import static net.runelite.api.ItemID.COMBAT_BRACELET; import static net.runelite.api.ItemID.CREAM_ROBE_TOP; import static net.runelite.api.ItemID.DEATH_TIARA; import static net.runelite.api.ItemID.DESERT_SHIRT; import static net.runelite.api.ItemID.DHAROKS_GREATAXE_0; import static net.runelite.api.ItemID.DHAROKS_GREATAXE_100; import static net.runelite.api.ItemID.DHAROKS_HELM_0; import static net.runelite.api.ItemID.DHAROKS_HELM_100; import static net.runelite.api.ItemID.DHAROKS_PLATEBODY_0; import static net.runelite.api.ItemID.DHAROKS_PLATEBODY_100; import static net.runelite.api.ItemID.DHAROKS_PLATELEGS_0; import static net.runelite.api.ItemID.DHAROKS_PLATELEGS_100; import static net.runelite.api.ItemID.DIAMOND_BRACELET; import static net.runelite.api.ItemID.DIAMOND_RING; import static net.runelite.api.ItemID.DRAGONSTONE_AMULET; import static net.runelite.api.ItemID.DRAGONSTONE_RING; import static net.runelite.api.ItemID.DRAGON_2H_SWORD; import static net.runelite.api.ItemID.DRAGON_AXE; import static net.runelite.api.ItemID.DRAGON_BATTLEAXE; import static net.runelite.api.ItemID.DRAGON_BOOTS; import static net.runelite.api.ItemID.DRAGON_CHAINBODY_3140; import static net.runelite.api.ItemID.DRAGON_DEFENDER; import static net.runelite.api.ItemID.DRAGON_MED_HELM; import static net.runelite.api.ItemID.DRAGON_NECKLACE; import static net.runelite.api.ItemID.DRAGON_PICKAXE; import static net.runelite.api.ItemID.DRAGON_PLATESKIRT; import static net.runelite.api.ItemID.DRAGON_SPEAR; import static net.runelite.api.ItemID.DRAGON_SQ_SHIELD; import static net.runelite.api.ItemID.ELEMENTAL_SHIELD; import static net.runelite.api.ItemID.EMERALD_AMULET; import static net.runelite.api.ItemID.EMERALD_RING; import static net.runelite.api.ItemID.FIRE_BATTLESTAFF; import static net.runelite.api.ItemID.FIRE_CAPE; import static net.runelite.api.ItemID.FLARED_TROUSERS; import static net.runelite.api.ItemID.GOLD_NECKLACE; import static net.runelite.api.ItemID.GOLD_RING; import static net.runelite.api.ItemID.GRANITE_SHIELD; import static net.runelite.api.ItemID.GREEN_BOATER; import static net.runelite.api.ItemID.GREEN_BOOTS; import static net.runelite.api.ItemID.GREEN_DHIDE_BODY; import static net.runelite.api.ItemID.GREEN_DHIDE_CHAPS; import static net.runelite.api.ItemID.GREEN_HAT; import static net.runelite.api.ItemID.GREEN_HEADBAND; import static net.runelite.api.ItemID.GREEN_ROBE_BOTTOMS; import static net.runelite.api.ItemID.GREEN_ROBE_TOP; import static net.runelite.api.ItemID.GREEN_SLAYER_HELMET; import static net.runelite.api.ItemID.GREEN_SLAYER_HELMET_I; import static net.runelite.api.ItemID.GUTHANS_CHAINSKIRT_0; import static net.runelite.api.ItemID.GUTHANS_CHAINSKIRT_100; import static net.runelite.api.ItemID.GUTHANS_HELM_0; import static net.runelite.api.ItemID.GUTHANS_HELM_100; import static net.runelite.api.ItemID.GUTHANS_PLATEBODY_0; import static net.runelite.api.ItemID.GUTHANS_PLATEBODY_100; import static net.runelite.api.ItemID.GUTHANS_WARSPEAR_0; import static net.runelite.api.ItemID.GUTHANS_WARSPEAR_100; import static net.runelite.api.ItemID.GUTHIX_MITRE; import static net.runelite.api.ItemID.GUTHIX_STOLE; import static net.runelite.api.ItemID.HAM_BOOTS; import static net.runelite.api.ItemID.HAM_ROBE; import static net.runelite.api.ItemID.HARDLEATHER_BODY; import static net.runelite.api.ItemID.HELM_OF_NEITIZNOT; import static net.runelite.api.ItemID.HOLY_BOOK; import static net.runelite.api.ItemID.IBANS_STAFF; import static net.runelite.api.ItemID.IBANS_STAFF_U; import static net.runelite.api.ItemID.IRON_2H_SWORD; import static net.runelite.api.ItemID.IRON_CHAINBODY; import static net.runelite.api.ItemID.IRON_FULL_HELM; import static net.runelite.api.ItemID.IRON_KITESHIELD; import static net.runelite.api.ItemID.IRON_MED_HELM; import static net.runelite.api.ItemID.IRON_PICKAXE; import static net.runelite.api.ItemID.IRON_PLATEBODY; import static net.runelite.api.ItemID.IRON_PLATELEGS; import static net.runelite.api.ItemID.IRON_PLATESKIRT; import static net.runelite.api.ItemID.IRON_SCIMITAR; import static net.runelite.api.ItemID.IRON_WARHAMMER; import static net.runelite.api.ItemID.KARILS_COIF_0; import static net.runelite.api.ItemID.KARILS_COIF_100; import static net.runelite.api.ItemID.KARILS_CROSSBOW_0; import static net.runelite.api.ItemID.KARILS_CROSSBOW_100; import static net.runelite.api.ItemID.KARILS_LEATHERSKIRT_0; import static net.runelite.api.ItemID.KARILS_LEATHERSKIRT_100; import static net.runelite.api.ItemID.KARILS_LEATHERTOP_0; import static net.runelite.api.ItemID.KARILS_LEATHERTOP_100; import static net.runelite.api.ItemID.LAVA_BATTLESTAFF; import static net.runelite.api.ItemID.LEATHER_BOOTS; import static net.runelite.api.ItemID.LEATHER_CHAPS; import static net.runelite.api.ItemID.LEATHER_COWL; import static net.runelite.api.ItemID.LEATHER_GLOVES; import static net.runelite.api.ItemID.LONGBOW; import static net.runelite.api.ItemID.MAGIC_LONGBOW; import static net.runelite.api.ItemID.MAPLE_LONGBOW; import static net.runelite.api.ItemID.MAPLE_SHORTBOW; import static net.runelite.api.ItemID.MENAPHITE_PURPLE_HAT; import static net.runelite.api.ItemID.MENAPHITE_PURPLE_ROBE; import static net.runelite.api.ItemID.MENAPHITE_PURPLE_TOP; import static net.runelite.api.ItemID.MIND_SHIELD; import static net.runelite.api.ItemID.MITHRIL_CHAINBODY; import static net.runelite.api.ItemID.MITHRIL_FULL_HELM; import static net.runelite.api.ItemID.MITHRIL_MED_HELM; import static net.runelite.api.ItemID.MITHRIL_PICKAXE; import static net.runelite.api.ItemID.MITHRIL_PLATEBODY; import static net.runelite.api.ItemID.MITHRIL_PLATELEGS; import static net.runelite.api.ItemID.MITHRIL_PLATESKIRT; import static net.runelite.api.ItemID.MITHRIL_SCIMITAR; import static net.runelite.api.ItemID.MYSTIC_FIRE_STAFF; import static net.runelite.api.ItemID.MYSTIC_GLOVES; import static net.runelite.api.ItemID.MYSTIC_HAT; import static net.runelite.api.ItemID.MYSTIC_ROBE_BOTTOM; import static net.runelite.api.ItemID.MYSTIC_ROBE_BOTTOM_DARK; import static net.runelite.api.ItemID.MYSTIC_ROBE_TOP; import static net.runelite.api.ItemID.MYSTIC_ROBE_TOP_DARK; import static net.runelite.api.ItemID.NEW_CRYSTAL_BOW_I; import static net.runelite.api.ItemID.OAK_LONGBOW; import static net.runelite.api.ItemID.OAK_SHORTBOW; import static net.runelite.api.ItemID.OBSIDIAN_CAPE; import static net.runelite.api.ItemID.ORANGE_BOATER; import static net.runelite.api.ItemID.PHARAOHS_SCEPTRE_3; import static net.runelite.api.ItemID.PINK_BOATER; import static net.runelite.api.ItemID.PINK_ROBE_TOP; import static net.runelite.api.ItemID.PINK_SKIRT; import static net.runelite.api.ItemID.PIRATE_BANDANA; import static net.runelite.api.ItemID.PIRATE_BANDANA_7124; import static net.runelite.api.ItemID.PIRATE_BANDANA_7130; import static net.runelite.api.ItemID.PIRATE_BANDANA_7136; import static net.runelite.api.ItemID.PROSELYTE_HAUBERK; import static net.runelite.api.ItemID.PURPLE_BOATER; import static net.runelite.api.ItemID.PURPLE_GLOVES; import static net.runelite.api.ItemID.PURPLE_SLAYER_HELMET; import static net.runelite.api.ItemID.PURPLE_SLAYER_HELMET_I; import static net.runelite.api.ItemID.RED_BOATER; import static net.runelite.api.ItemID.RED_DHIDE_CHAPS; import static net.runelite.api.ItemID.RED_HEADBAND; import static net.runelite.api.ItemID.RED_SLAYER_HELMET; import static net.runelite.api.ItemID.RED_SLAYER_HELMET_I; import static net.runelite.api.ItemID.RING_OF_DUELING1; import static net.runelite.api.ItemID.RING_OF_DUELING2; import static net.runelite.api.ItemID.RING_OF_DUELING3; import static net.runelite.api.ItemID.RING_OF_DUELING4; import static net.runelite.api.ItemID.RING_OF_DUELING5; import static net.runelite.api.ItemID.RING_OF_DUELING6; import static net.runelite.api.ItemID.RING_OF_DUELING7; import static net.runelite.api.ItemID.RING_OF_DUELING8; import static net.runelite.api.ItemID.RING_OF_FORGING; import static net.runelite.api.ItemID.RING_OF_LIFE; import static net.runelite.api.ItemID.RING_OF_WEALTH; import static net.runelite.api.ItemID.RING_OF_WEALTH_1; import static net.runelite.api.ItemID.RING_OF_WEALTH_2; import static net.runelite.api.ItemID.RING_OF_WEALTH_3; import static net.runelite.api.ItemID.RING_OF_WEALTH_4; import static net.runelite.api.ItemID.RING_OF_WEALTH_5; import static net.runelite.api.ItemID.ROLLING_PIN; import static net.runelite.api.ItemID.RUBY_AMULET; import static net.runelite.api.ItemID.RUBY_RING; import static net.runelite.api.ItemID.RUNE_AXE; import static net.runelite.api.ItemID.RUNE_BOOTS; import static net.runelite.api.ItemID.RUNE_CROSSBOW; import static net.runelite.api.ItemID.RUNE_FULL_HELM; import static net.runelite.api.ItemID.RUNE_HALBERD; import static net.runelite.api.ItemID.RUNE_HELM_H1; import static net.runelite.api.ItemID.RUNE_HELM_H5; import static net.runelite.api.ItemID.RUNE_KITESHIELD; import static net.runelite.api.ItemID.RUNE_LONGSWORD; import static net.runelite.api.ItemID.RUNE_PICKAXE; import static net.runelite.api.ItemID.RUNE_PLATEBODY; import static net.runelite.api.ItemID.RUNE_PLATELEGS; import static net.runelite.api.ItemID.RUNE_PLATESKIRT; import static net.runelite.api.ItemID.RUNE_SHIELD_H1; import static net.runelite.api.ItemID.RUNE_SHIELD_H2; import static net.runelite.api.ItemID.RUNE_SHIELD_H3; import static net.runelite.api.ItemID.RUNE_SHIELD_H4; import static net.runelite.api.ItemID.RUNE_SHIELD_H5; import static net.runelite.api.ItemID.RUNE_SPEAR; import static net.runelite.api.ItemID.RUNE_WARHAMMER; import static net.runelite.api.ItemID.SAPPHIRE_AMULET; import static net.runelite.api.ItemID.SAPPHIRE_NECKLACE; import static net.runelite.api.ItemID.SAPPHIRE_RING; import static net.runelite.api.ItemID.SARADOMIN_CROZIER; import static net.runelite.api.ItemID.SARADOMIN_MITRE; import static net.runelite.api.ItemID.SARADOMIN_STOLE; import static net.runelite.api.ItemID.SEERCULL; import static net.runelite.api.ItemID.SHADOW_SWORD; import static net.runelite.api.ItemID.SILVER_SICKLE; import static net.runelite.api.ItemID.SLAYER_HELMET; import static net.runelite.api.ItemID.SLAYER_HELMET_I; import static net.runelite.api.ItemID.SLED_4084; import static net.runelite.api.ItemID.SNAKESKIN_BOOTS; import static net.runelite.api.ItemID.SNAKESKIN_CHAPS; import static net.runelite.api.ItemID.SPINED_CHAPS; import static net.runelite.api.ItemID.SPLITBARK_BODY; import static net.runelite.api.ItemID.SPLITBARK_LEGS; import static net.runelite.api.ItemID.SPOTTED_CAPE; import static net.runelite.api.ItemID.SPOTTED_CAPE_10073; import static net.runelite.api.ItemID.STAFF; import static net.runelite.api.ItemID.STAFF_OF_AIR; import static net.runelite.api.ItemID.STAFF_OF_WATER; import static net.runelite.api.ItemID.STEEL_AXE; import static net.runelite.api.ItemID.STEEL_FULL_HELM; import static net.runelite.api.ItemID.STEEL_KITESHIELD; import static net.runelite.api.ItemID.STEEL_LONGSWORD; import static net.runelite.api.ItemID.STEEL_MACE; import static net.runelite.api.ItemID.STEEL_MED_HELM; import static net.runelite.api.ItemID.STEEL_PICKAXE; import static net.runelite.api.ItemID.STEEL_PLATEBODY; import static net.runelite.api.ItemID.STEEL_PLATESKIRT; import static net.runelite.api.ItemID.STEEL_SQ_SHIELD; import static net.runelite.api.ItemID.STUDDED_BODY; import static net.runelite.api.ItemID.STUDDED_CHAPS; import static net.runelite.api.ItemID.TEAM1_CAPE; import static net.runelite.api.ItemID.TEAM50_CAPE; import static net.runelite.api.ItemID.TIARA; import static net.runelite.api.ItemID.TOKTZKETXIL; import static net.runelite.api.ItemID.TOKTZXILUL; import static net.runelite.api.ItemID.TORAGS_HAMMERS_0; import static net.runelite.api.ItemID.TORAGS_HAMMERS_100; import static net.runelite.api.ItemID.TORAGS_HELM_0; import static net.runelite.api.ItemID.TORAGS_HELM_100; import static net.runelite.api.ItemID.TORAGS_PLATEBODY_0; import static net.runelite.api.ItemID.TORAGS_PLATEBODY_100; import static net.runelite.api.ItemID.TORAGS_PLATELEGS_0; import static net.runelite.api.ItemID.TORAGS_PLATELEGS_100; import static net.runelite.api.ItemID.TURQUOISE_ROBE_BOTTOMS; import static net.runelite.api.ItemID.TURQUOISE_SLAYER_HELMET; import static net.runelite.api.ItemID.TURQUOISE_SLAYER_HELMET_I; import static net.runelite.api.ItemID.UNHOLY_BOOK; import static net.runelite.api.ItemID.VERACS_BRASSARD_0; import static net.runelite.api.ItemID.VERACS_BRASSARD_100; import static net.runelite.api.ItemID.VERACS_FLAIL_0; import static net.runelite.api.ItemID.VERACS_FLAIL_100; import static net.runelite.api.ItemID.VERACS_HELM_0; import static net.runelite.api.ItemID.VERACS_HELM_100; import static net.runelite.api.ItemID.VERACS_PLATESKIRT_0; import static net.runelite.api.ItemID.VERACS_PLATESKIRT_100; import static net.runelite.api.ItemID.WHITE_APRON; import static net.runelite.api.ItemID.WHITE_BOATER; import static net.runelite.api.ItemID.WHITE_HEADBAND; import static net.runelite.api.ItemID.ZAMORAK_CROZIER; import static net.runelite.api.ItemID.ZAMORAK_FULL_HELM; import static net.runelite.api.ItemID.ZAMORAK_GODSWORD; import static net.runelite.api.ItemID.ZAMORAK_MITRE; import static net.runelite.api.ItemID.ZAMORAK_STOLE; import net.runelite.api.coords.LocalPoint; import net.runelite.api.coords.WorldPoint; import static net.runelite.client.plugins.cluescrolls.ClueScrollOverlay.TITLED_CONTENT_COLOR; import net.runelite.client.plugins.cluescrolls.ClueScrollPlugin; import static net.runelite.client.plugins.cluescrolls.ClueScrollPlugin.EMOTE_IMAGE; import net.runelite.client.plugins.cluescrolls.clues.emote.AllRequirementsCollection; import net.runelite.client.plugins.cluescrolls.clues.emote.AnyRequirementCollection; import net.runelite.client.plugins.cluescrolls.clues.emote.Emote; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.ANGRY; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.BECKON; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.BLOW_KISS; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.BOW; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.BULL_ROARER; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.CHEER; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.CLAP; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.CRY; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.DANCE; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.FLAP; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.GOBLIN_SALUTE; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.HEADBANG; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.JIG; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.JUMP_FOR_JOY; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.LAUGH; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.NO; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.PANIC; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.PUSH_UP; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.RASPBERRY; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.SALUTE; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.SHRUG; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.SLAP_HEAD; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.SPIN; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.STOMP; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.THINK; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.WAVE; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.YAWN; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.YES; import net.runelite.client.plugins.cluescrolls.clues.emote.ItemRequirement; import net.runelite.client.plugins.cluescrolls.clues.emote.RangeItemRequirement; import net.runelite.client.plugins.cluescrolls.clues.emote.SingleItemRequirement; import net.runelite.client.plugins.cluescrolls.clues.emote.SlotLimitationRequirement; import net.runelite.client.ui.overlay.OverlayUtil; import net.runelite.client.ui.overlay.components.LineComponent; import net.runelite.client.ui.overlay.components.PanelComponent; import net.runelite.client.ui.overlay.components.TitleComponent; @Getter public class EmoteClue extends ClueScroll implements TextClueScroll, LocationClueScroll { private static final Set<EmoteClue> CLUES = ImmutableSet.of( new EmoteClue("Beckon on the east coast of the Kharazi Jungle. Beware of double agents! Equip any vestment stole and a heraldic rune shield.", new WorldPoint(2954, 2933, 0), BECKON, any("Any stole", item(GUTHIX_STOLE), item(SARADOMIN_STOLE), item(ZAMORAK_STOLE), item(ARMADYL_STOLE), item(BANDOS_STOLE), item(ANCIENT_STOLE)), any("Any heraldic rune shield", item(RUNE_SHIELD_H1), item(RUNE_SHIELD_H2), item(RUNE_SHIELD_H3), item(RUNE_SHIELD_H4), item(RUNE_SHIELD_H5))), new EmoteClue("Cheer in the Barbarian Agility Arena. Headbang before you talk to me. Equip a steel platebody, maple shortbow and a Wilderness cape.", new WorldPoint(2552, 3556, 0), CHEER, HEADBANG, item(STEEL_PLATEBODY), item(MAPLE_SHORTBOW), range("Any team cape", TEAM1_CAPE, TEAM50_CAPE)), new EmoteClue("Bow upstairs in the Monastery. Equip a completed prayer book.", new WorldPoint(3056, 3484, 1), BOW, any("Any god book", item(HOLY_BOOK), item(BOOK_OF_BALANCE), item(UNHOLY_BOOK), item(BOOK_OF_LAW), item(BOOK_OF_WAR), item(BOOK_OF_DARKNESS))), new EmoteClue("Cheer in the Shadow dungeon. Equip a rune crossbow, climbing boots and any mitre.", new WorldPoint(2629, 5071, 0), CHEER, any("Any mitre", item(GUTHIX_MITRE), item(SARADOMIN_MITRE), item(ZAMORAK_MITRE), item(ANCIENT_MITRE), item(BANDOS_MITRE), item(ARMADYL_MITRE)), item(RUNE_CROSSBOW), item(CLIMBING_BOOTS)), new EmoteClue("Cheer at the top of the agility pyramid. Beware of double agents! Equip a blue mystic robe top, and any rune heraldic shield.", new WorldPoint(3043, 4697, 3), CHEER, item(MYSTIC_ROBE_TOP), any("Any rune heraldic shield", item(RUNE_SHIELD_H1), item(RUNE_SHIELD_H2), item(RUNE_SHIELD_H3), item(RUNE_SHIELD_H4), item(RUNE_SHIELD_H5))), new EmoteClue("Dance in Iban's temple. Beware of double agents! Equip Iban's staff, a black mystic top, and a black mystic bottom.", new WorldPoint(2011, 4712, 0), DANCE, any("Any iban's staff", item(IBANS_STAFF), item(IBANS_STAFF_U)), item(MYSTIC_ROBE_TOP_DARK), item(MYSTIC_ROBE_BOTTOM_DARK)), new EmoteClue("Dance on the Fishing Platform. Equip barrows gloves, an amulet of glory and a dragon med helm.", new WorldPoint(2782, 3273, 0), DANCE, any("Any amulet of glory", item(AMULET_OF_GLORY), item(AMULET_OF_GLORY1), item(AMULET_OF_GLORY2), item(AMULET_OF_GLORY3), item(AMULET_OF_GLORY4), item(AMULET_OF_GLORY5), item(AMULET_OF_GLORY6)), item(BARROWS_GLOVES), item(DRAGON_MED_HELM)), new EmoteClue("Flap at the death altar. Beware of double agents! Equip a death tiara, a legend's cape and any ring of wealth.", new WorldPoint(2205, 4838, 0), FLAP, any("Any ring of wealth", item(RING_OF_WEALTH), item(RING_OF_WEALTH_1), item(RING_OF_WEALTH_2), item(RING_OF_WEALTH_3), item(RING_OF_WEALTH_4), item(RING_OF_WEALTH_5)), item(DEATH_TIARA), item(CAPE_OF_LEGENDS)), new EmoteClue("Headbang in the Fight Arena pub. Equip a pirate bandana, a dragonstone necklace and and a magic longbow.", new WorldPoint(2568, 3149, 0), HEADBANG, any("Any pirate bandana", item(PIRATE_BANDANA), item(PIRATE_BANDANA_7124), item(PIRATE_BANDANA_7130), item(PIRATE_BANDANA_7136)), item(DRAGON_NECKLACE), item(MAGIC_LONGBOW)), new EmoteClue("Do a jig at the barrow's chest. Beware of double agents! Equip any full barrows set.", new WorldPoint(3551, 9694, 0), JIG, any("Any full barrows set", all(range(AHRIMS_HOOD_100, AHRIMS_HOOD_0), range(AHRIMS_STAFF_100, AHRIMS_STAFF_0), range(AHRIMS_ROBETOP_100, AHRIMS_ROBETOP_0), range(AHRIMS_ROBESKIRT_100, AHRIMS_ROBESKIRT_0)), all(range(DHAROKS_HELM_100, DHAROKS_HELM_0), range(DHAROKS_GREATAXE_100, DHAROKS_GREATAXE_0), range(DHAROKS_PLATEBODY_100, DHAROKS_PLATEBODY_0), range(DHAROKS_PLATELEGS_100, DHAROKS_PLATELEGS_0)), all(range(GUTHANS_HELM_100, GUTHANS_HELM_0), range(GUTHANS_WARSPEAR_100, GUTHANS_WARSPEAR_0), range(GUTHANS_PLATEBODY_100, GUTHANS_PLATEBODY_0), range(GUTHANS_CHAINSKIRT_100, GUTHANS_CHAINSKIRT_0)), all(range(KARILS_COIF_100, KARILS_COIF_0), range(KARILS_CROSSBOW_100, KARILS_CROSSBOW_0), range(KARILS_LEATHERTOP_100, KARILS_LEATHERTOP_0), range(KARILS_LEATHERSKIRT_100, KARILS_LEATHERSKIRT_0)), all(range(TORAGS_HELM_100, TORAGS_HELM_0), range(TORAGS_HAMMERS_100, TORAGS_HAMMERS_0), range(TORAGS_PLATEBODY_100, TORAGS_PLATEBODY_0), range(TORAGS_PLATELEGS_100, TORAGS_PLATELEGS_0)), all(range(VERACS_HELM_100, VERACS_HELM_0), range(VERACS_FLAIL_100, VERACS_FLAIL_0), range(VERACS_BRASSARD_100, VERACS_BRASSARD_0), range(VERACS_PLATESKIRT_100, VERACS_PLATESKIRT_0)))), new EmoteClue("Jig at Jiggig. Beware of double agents! Equip a Rune spear, rune platelegs and any rune heraldic helm.", new WorldPoint(2477, 3047, 0), JIG, range("Any rune heraldic helm", RUNE_HELM_H1, RUNE_HELM_H5), item(RUNE_SPEAR), item(RUNE_PLATELEGS)), new EmoteClue("Cheer at the games room. Have nothing equipped at all when you do.", new WorldPoint(2207, 4952, 0), CHEER, emptySlot("Nothing at all", HEAD, CAPE, AMULET, WEAPON, BODY, SHIELD, LEGS, GLOVES, BOOTS, RING)), new EmoteClue("Panic on the pier where you catch the Fishing trawler. Have nothing equipped at all when you do.", new WorldPoint(2676, 3169, 0), PANIC, emptySlot("Nothing at all", HEAD, CAPE, AMULET, WEAPON, BODY, SHIELD, LEGS, GLOVES, BOOTS, RING)), new EmoteClue("Panic in the heart of the Haunted Woods. Beware of double agents! Have no items equipped when you do.", new WorldPoint(3611, 3492, 0), PANIC, emptySlot("Nothing at all", HEAD, CAPE, AMULET, WEAPON, BODY, SHIELD, LEGS, GLOVES, BOOTS, RING)), new EmoteClue("Show your anger towards the Statue of Saradomin in Ellamaria's garden. Beware of double agents! Equip a zamorak godsword.", new WorldPoint(3230, 3478, 0), ANGRY, item(ZAMORAK_GODSWORD)), new EmoteClue("Show your anger at the Wise old man. Beware of double agents! Equip an abyssal whip, a legend's cape and some spined chaps.", new WorldPoint(3088, 3254, 0), ANGRY, item(ABYSSAL_WHIP), item(CAPE_OF_LEGENDS), item(SPINED_CHAPS)), new EmoteClue("Beckon in the Digsite, near the eastern winch. Bow before you talk to me. Equip a green gnome hat, snakeskin boots and an iron pickaxe.", new WorldPoint(3370, 3425, 0), BECKON, BOW, item(GREEN_HAT), item(SNAKESKIN_BOOTS), item(IRON_PICKAXE)), new EmoteClue("Beckon in Tai Bwo Wannai. Clap before you talk to me. Equip green dragonhide chaps, a ring of dueling and a mithril medium helmet.", new WorldPoint(2784, 3065, 0), BECKON, CLAP, item(GREEN_DHIDE_CHAPS), any("Ring of dueling", item(RING_OF_DUELING1), item(RING_OF_DUELING2), item(RING_OF_DUELING3), item(RING_OF_DUELING4), item(RING_OF_DUELING5), item(RING_OF_DUELING6), item(RING_OF_DUELING7), item(RING_OF_DUELING8)), item(MITHRIL_MED_HELM)), new EmoteClue("Beckon in the combat ring of Shayzien. Show your anger before you talk to me. Equip an adamant platebody, adamant full helm and adamant platelegs.", new WorldPoint(1545, 3594, 0), BECKON, ANGRY, item(ADAMANT_PLATELEGS), item(ADAMANT_PLATEBODY), item(ADAMANT_FULL_HELM)), new EmoteClue("Bow near Lord Iorwerth. Beware of double agents! Equip a new imbued crystal bow.", new WorldPoint(2205, 3252, 0), BOW, item(NEW_CRYSTAL_BOW_I)), new EmoteClue("Bow outside the entrance to the Legends' Guild. Equip iron platelegs, an emerald amulet and an oak longbow.", new WorldPoint(2729, 3349, 0), BOW, item(IRON_PLATELEGS), item(OAK_LONGBOW), item(EMERALD_AMULET)), new EmoteClue("Bow on the ground floor of the Legend's guild. Equip Legend's cape, a dragon battleaxe and an amulet of glory.", new WorldPoint(2728, 3377, 0), BOW, item(CAPE_OF_LEGENDS), item(DRAGON_BATTLEAXE), item(AMULET_OF_GLORY)), new EmoteClue("Bow in the ticket office of the Duel Arena. Equip an iron chain body, leather chaps and coif.", new WorldPoint(3314, 3241, 0), BOW, item(IRON_CHAINBODY), item(LEATHER_CHAPS), item(COIF)), new EmoteClue("Bow at the top of the lighthouse. Beware of double agents! Equip a blue dragonhide body, blue dragonhide vambraces and no jewelry.", new WorldPoint(2511, 3641, 2), BOW, item(BLUE_DHIDE_BODY), item(BLUE_DHIDE_VAMB), emptySlot("No jewelry", AMULET, RING)), new EmoteClue("Blow a kiss between the tables in Shilo Village bank. Beware of double agents! Equip a blue mystic hat, bone spear and rune platebody.", new WorldPoint(2851, 2954, 0), BLOW_KISS, item(MYSTIC_HAT), item(BONE_SPEAR), item(RUNE_PLATEBODY)), new EmoteClue("Blow a kiss in the heart of the lava maze. Equip black dragonhide chaps, a spotted cape and a rolling pin.", new WorldPoint(3069, 3861, 0), BLOW_KISS, item(BLACK_DHIDE_CHAPS), any("Spotted cape", item(SPOTTED_CAPE), item(SPOTTED_CAPE_10073)), item(ROLLING_PIN)), new EmoteClue("Blow a kiss outside K'ril Tsutsaroth's chamber. Beware of double agents! Equip a zamorak full helm and the shadow sword.", new WorldPoint(2925, 5333, 0), BLOW_KISS, item(ZAMORAK_FULL_HELM), item(SHADOW_SWORD)), new EmoteClue("Cheer at the Druids' Circle. Equip a blue wizard hat, a bronze two-handed sword and HAM boots.", new WorldPoint(2925, 3484, 0), CHEER, item(BLUE_WIZARD_HAT), item(BRONZE_2H_SWORD), item(HAM_BOOTS)), new EmoteClue("Cheer in the Edgeville general store. Dance before you talk to me. Equip a brown apron, leather boots and leather gloves.", new WorldPoint(3080, 3509, 0), CHEER, DANCE, item(BROWN_APRON), item(LEATHER_BOOTS), item(LEATHER_GLOVES)), new EmoteClue("Cheer in the Ogre Pen in the Training Camp. Show you are angry before you talk to me. Equip a green dragonhide body and chaps and a steel square shield.", new WorldPoint(2527, 3375, 0), CHEER, ANGRY, item(GREEN_DHIDE_BODY), item(GREEN_DHIDE_CHAPS), item(STEEL_SQ_SHIELD)), new EmoteClue("Cheer in the Entrana church. Beware of double agents! Equip a full set of black dragonhide armour.", new WorldPoint(2852, 3349, 0), CHEER, item(BLACK_DHIDE_VAMB), item(BLACK_DHIDE_CHAPS), item(BLACK_DHIDE_BODY)), new EmoteClue("Cheer for the monks at Port Sarim. Equip a coif, steel plateskirt and a sapphire necklace.", new WorldPoint(3047, 3237, 0), CHEER, item(COIF), item(STEEL_PLATESKIRT), item(SAPPHIRE_NECKLACE)), new EmoteClue("Clap in the main exam room in the Exam Centre. Equip a white apron, green gnome boots and leather gloves.", new WorldPoint(3361, 3339, 0), CLAP, item(WHITE_APRON), item(GREEN_BOOTS), item(LEATHER_GLOVES)), new EmoteClue("Clap on the causeway to the Wizards' Tower. Equip an iron medium helmet, emerald ring and a white apron.", new WorldPoint(3113, 3196, 0), CLAP, item(IRON_MED_HELM), item(EMERALD_RING), item(WHITE_APRON)), new EmoteClue("Clap on the top level of the mill, north of East Ardougne. Equip a blue gnome robe top, HAM robe bottom and an unenchanted tiara.", new WorldPoint(2635, 3385, 3), CLAP, item(BLUE_ROBE_TOP), item(HAM_ROBE), item(TIARA)), new EmoteClue("Clap in Seers court house. Spin before you talk to me. Equip an adamant halberd, blue mystic robe bottom and a diamond ring.", new WorldPoint(2735, 3469, 0), CLAP, SPIN, item(ADAMANT_HALBERD), item(MYSTIC_ROBE_BOTTOM), item(DIAMOND_RING)), new EmoteClue("Clap in the magic axe hut. Beware of double agents. Equip only some flared trousers.", new WorldPoint(3191, 3960, 0), CLAP, item(FLARED_TROUSERS), emptySlot("Nothing else", HEAD, CAPE, AMULET, WEAPON, BODY, SHIELD, GLOVES, BOOTS, RING)), new EmoteClue("Cry in the Catherby Ranging shop. Bow before you talk to me. Equip blue gnome boots, a hard leather body and an unblessed silver sickle.", new WorldPoint(2823, 3443, 0), CRY, BOW, item(BLUE_BOOTS), item(HARDLEATHER_BODY), item(SILVER_SICKLE)), new EmoteClue("Cry on the shore of Catherby beach. Laugh before you talk to me, equip an adamant sq shield, a bone dagger and mithril platebody.", new WorldPoint(2852, 3429, 0), CRY, LAUGH, item(ADAMANT_SQ_SHIELD), item(BONE_DAGGER), item(MITHRIL_PLATEBODY)), new EmoteClue("Cry on top of the western tree in the Gnome Agility Arena. Indicate 'no' before you talk to me. Equip a steel kiteshield, ring of forging and green dragonhide chaps.", new WorldPoint(2473, 3420, 2), CRY, NO, item(STEEL_KITESHIELD), item(RING_OF_FORGING), item(GREEN_DHIDE_CHAPS)), new EmoteClue("Cry in the TzHaar gem store. Beware of double agents! Equip a fire cape and TokTz-Xil-Ul.", new WorldPoint(2463, 5149, 0), CRY, item(FIRE_CAPE), item(TOKTZXILUL)), new EmoteClue("Cry in the Draynor Village jail. Jump for joy before you talk to me. Equip an adamant sword, a sapphire amulet and an adamant plateskirt.", new WorldPoint(3128, 3245, 0), CRY, JUMP_FOR_JOY, item(ADAMANT_SWORD), item(SAPPHIRE_AMULET), item(ADAMANT_PLATESKIRT)), new EmoteClue("Dance at the crossroads north of Draynor. Equip an iron chain body, a sapphire ring and a longbow.", new WorldPoint(3109, 3294, 0), DANCE, item(IRON_CHAINBODY), item(SAPPHIRE_RING), item(LONGBOW)), new EmoteClue("Dance in the Party Room. Equip a steel full helmet, steel platebody and an iron plateskirt.", new WorldPoint(3045, 3376, 0), DANCE, item(STEEL_FULL_HELM), item(STEEL_PLATEBODY), item(IRON_PLATESKIRT)), new EmoteClue("Dance in the shack in Lumbridge Swamp. Equip a bronze dagger, iron full helmet and a gold ring.", new WorldPoint(3203, 3169, 0), DANCE, item(BRONZE_DAGGER), item(IRON_FULL_HELM), item(GOLD_RING)), new EmoteClue("Dance in the dark caves beneath Lumbridge Swamp. Blow a kiss before you talk to me. Equip an air staff, Bronze full helm and an amulet of power.", new WorldPoint(3223, 9597, 0), DANCE, BLOW_KISS, item(STAFF_OF_AIR), item(BRONZE_FULL_HELM), item(AMULET_OF_POWER)), new EmoteClue("Dance at the cat-doored pyramid in Sophanem. Beware of double agents! Equip a ring of life, an uncharged amulet of glory and an adamant two-handed sword.", new WorldPoint(3294, 2781, 0), DANCE, item(RING_OF_LIFE), item(AMULET_OF_GLORY), item(ADAMANT_2H_SWORD)), new EmoteClue("Dance in the centre of Canifis. Bow before you talk to me. Equip a green gnome robe top, mithril plate legs and an iron two-handed sword.", new WorldPoint(3492, 3488, 0), DANCE, BOW, item(GREEN_ROBE_TOP), item(MITHRIL_PLATELEGS), item(IRON_2H_SWORD)), new EmoteClue("Dance in the King Black Dragon's lair. Beware of double agents! Equip a black dragonhide body, black dragonhide vambs and a black dragon mask.", new WorldPoint(2271, 4680, 0), DANCE, item(BLACK_DHIDE_BODY), item(BLACK_DHIDE_VAMB), item(BLACK_DRAGON_MASK)), new EmoteClue("Dance at the entrance to the Grand Exchange. Equip a pink skirt, pink robe top and a body tiara.", new WorldPoint(3165, 3467, 0), DANCE, item(PINK_SKIRT), item(PINK_ROBE_TOP), item(BODY_TIARA)), new EmoteClue("Goblin Salute in the Goblin Village. Beware of double agents! Equip a bandos godsword, a bandos cloak and a bandos platebody.", new WorldPoint(2956, 3505, 0), GOBLIN_SALUTE, item(BANDOS_PLATEBODY), item(BANDOS_CLOAK), item(BANDOS_GODSWORD)), new EmoteClue("Headbang in the mine north of Al Kharid. Equip a desert shirt, leather gloves and leather boots.", new WorldPoint(3299, 3289, 0), HEADBANG, item(DESERT_SHIRT), item(LEATHER_GLOVES), item(LEATHER_BOOTS)), new EmoteClue("Headbang at the exam center. Beware of double agents! Equip a mystic fire staff, a diamond bracelet and rune boots.", new WorldPoint(3362, 3340, 0), HEADBANG, item(MYSTIC_FIRE_STAFF), item(DIAMOND_BRACELET), item(RUNE_BOOTS)), new EmoteClue("Headbang at the top of Slayer Tower. Equip a seercull, a combat bracelet and helm of Neitiznot.", new WorldPoint(3115, 3420, 0), HEADBANG, item(SEERCULL), item(COMBAT_BRACELET), item(HELM_OF_NEITIZNOT)), new EmoteClue("Dance a jig by the entrance to the Fishing Guild. Equip an emerald ring, a sapphire amulet, and a bronze chain body.", new WorldPoint(2610, 3391, 0), JIG, item(EMERALD_RING), item(SAPPHIRE_AMULET), item(BRONZE_CHAINBODY)), new EmoteClue("Dance a jig under Shantay's Awning. Bow before you talk to me. Equip a pointed blue snail helmet, an air staff and a bronze square shield.", new WorldPoint(3304, 3124, 0), JIG, BOW, item(BRUISE_BLUE_SNELM_3343), item(STAFF_OF_AIR), item(BRONZE_SQ_SHIELD)), new EmoteClue("Do a jig in Varrock's rune store. Equip an air tiara and a staff of water.", new WorldPoint(3253, 3401, 0), JIG, item(AIR_TIARA), item(STAFF_OF_WATER)), new EmoteClue("Jump for joy at the beehives. Equip a desert shirt, green gnome robe bottoms and a steel axe.", new WorldPoint(2759, 3445, 0), JUMP_FOR_JOY, item(DESERT_SHIRT), item(GREEN_ROBE_BOTTOMS), item(STEEL_AXE)), new EmoteClue("Jump for joy in Yanille bank. Dance a jig before you talk to me. Equip a brown apron, adamantite medium helmet and snakeskin chaps.", new WorldPoint(2610, 3092, 0), JUMP_FOR_JOY, JIG, item(BROWN_APRON), item(ADAMANT_MED_HELM), item(SNAKESKIN_CHAPS)), new EmoteClue("Jump for joy in the TzHaar sword shop. Shrug before you talk to me. Equip a Steel longsword, Blue D'hide body and blue mystic gloves.", new WorldPoint(2477, 5146, 0), JUMP_FOR_JOY, SHRUG, item(STEEL_LONGSWORD), item(BLUE_DHIDE_BODY), item(MYSTIC_GLOVES)), new EmoteClue("Jump for joy in the Ancient Cavern. Equip a granite shield, splitbark body and any rune heraldic helm.", new WorldPoint(2339, 6787, 0), JUMP_FOR_JOY, item(GRANITE_SHIELD), item(SPLITBARK_BODY), range("Any rune heraldic helm", RUNE_HELM_H1, RUNE_HELM_H5)), new EmoteClue("Jump for joy at the Neitiznot rune rock. Equip Rune boots, a proselyte hauberk and a dragonstone ring.", new WorldPoint(2375, 3850, 0), JUMP_FOR_JOY, item(RUNE_BOOTS), item(PROSELYTE_HAUBERK), item(DRAGONSTONE_RING)), new EmoteClue("Jump for joy in the centre of Zul-Andra. Beware of double agents! Equip a dragon 2h sword, bandos boots and an obsidian cape.", new WorldPoint(2199, 3056, 0), JUMP_FOR_JOY, item(DRAGON_2H_SWORD), item(BANDOS_BOOTS), item(OBSIDIAN_CAPE)), new EmoteClue("Laugh by the fountain of heroes. Equip splitbark legs, dragon boots and a Rune longsword.", new WorldPoint(2716, 6584, 0), LAUGH, item(SPLITBARK_LEGS), item(DRAGON_BOOTS), item(RUNE_LONGSWORD)), new EmoteClue("Laugh in Jokul's tent in the Mountain Camp. Beware of double agents! Equip a rune full helmet, blue dragonhide chaps and a fire battlestaff.", new WorldPoint(2812, 3681, 0), LAUGH, item(RUNE_FULL_HELM), item(BLUE_DHIDE_CHAPS), item(FIRE_BATTLESTAFF)), new EmoteClue("Laugh at the crossroads south of the Sinclair Mansion. Equip a cowl, a blue wizard robe top and an iron scimitar.", new WorldPoint(2741, 3536, 0), LAUGH, item(LEATHER_COWL), item(BLUE_WIZARD_ROBE), item(IRON_SCIMITAR)), new EmoteClue("Laugh in front of the gem store in Ardougne market. Equip a Castlewars bracelet, a dragonstone amulet and a ring of forging.", new WorldPoint(2666, 3304, 0), LAUGH, any("Castle wars bracelet", range(CASTLE_WARS_BRACELET3, CASTLE_WARS_BRACELET1)), item(DRAGONSTONE_AMULET), item(RING_OF_FORGING)), new EmoteClue("Panic in the Limestone Mine. Equip bronze platelegs, a steel pickaxe and a steel medium helmet.", new WorldPoint(3372, 3498, 0), PANIC, item(BRONZE_PLATELEGS), item(STEEL_PICKAXE), item(STEEL_MED_HELM)), new EmoteClue("Panic by the mausoleum in Morytania. Wave before you speak to me. Equip a mithril plate skirt, a maple longbow and no boots.", new WorldPoint(3504, 3576, 0), PANIC, WAVE, item(MITHRIL_PLATESKIRT), item(MAPLE_LONGBOW), emptySlot("No boots", BOOTS)), new EmoteClue("Panic on the Wilderness volcano bridge. Beware of double agents! Equip any headband and crozier.", new WorldPoint(3368, 3935, 0), PANIC, any("Any headband", range(RED_HEADBAND, BROWN_HEADBAND), range(WHITE_HEADBAND, GREEN_HEADBAND)), any("Any crozier", item(ANCIENT_CROZIER), item(ARMADYL_CROZIER), item(BANDOS_CROZIER), range(SARADOMIN_CROZIER, ZAMORAK_CROZIER))), new EmoteClue("Panic by the pilot on White Wolf Mountain. Beware of double agents! Equip mithril platelegs, a ring of life and a rune axe.", new WorldPoint(2847, 3499, 0), PANIC, item(MITHRIL_PLATELEGS), item(RING_OF_LIFE), item(RUNE_AXE)), new EmoteClue("Panic by the big egg where no one dare goes and the ground is burnt. Beware of double agents! Equip a dragon med helm, a TokTz-Ket-Xil, a brine sabre, rune platebody and an uncharged amulet of glory.", new WorldPoint(3227, 3831, 0), PANIC, item(DRAGON_MED_HELM), item(TOKTZKETXIL), item(BRINE_SABRE), item(RUNE_PLATEBODY), item(AMULET_OF_GLORY)), new EmoteClue("Panic at the area flowers meet snow. Equip Blue D'hide vambs, a dragon spear and a rune plateskirt.", new WorldPoint(2776, 3781, 0), PANIC, item(BLUE_DHIDE_VAMB), item(DRAGON_SPEAR), item(RUNE_PLATESKIRT), item(SLED_4084)), new EmoteClue("Do a push up at the bank of the Warrior's guild. Beware of double agents! Equip a dragon battleaxe, a dragon defender and a slayer helm of any kind.", new WorldPoint(2843, 3543, 0), PUSH_UP, item(DRAGON_BATTLEAXE), item(DRAGON_DEFENDER), any("Any slayer helmet", item(SLAYER_HELMET), item(BLACK_SLAYER_HELMET), item(GREEN_SLAYER_HELMET), item(PURPLE_SLAYER_HELMET), item(RED_SLAYER_HELMET), item(TURQUOISE_SLAYER_HELMET), item(SLAYER_HELMET_I), item(BLACK_SLAYER_HELMET_I), item(GREEN_SLAYER_HELMET_I), item(PURPLE_SLAYER_HELMET_I), item(RED_SLAYER_HELMET_I), item(TURQUOISE_SLAYER_HELMET_I))), new EmoteClue("Blow a raspberry at the bank of the Warrior's guild. Beware of double agents! Eqiup a dragon battleaxe, a dragon defender, and a slayer helmet of any kind.", new WorldPoint(2843, 3543, 0), RASPBERRY, item(DRAGON_BATTLEAXE), item(DRAGON_DEFENDER), any("Any slayer helmet", item(SLAYER_HELMET), item(BLACK_SLAYER_HELMET), item(GREEN_SLAYER_HELMET), item(PURPLE_SLAYER_HELMET), item(RED_SLAYER_HELMET), item(TURQUOISE_SLAYER_HELMET), item(SLAYER_HELMET_I), item(BLACK_SLAYER_HELMET_I), item(GREEN_SLAYER_HELMET_I), item(PURPLE_SLAYER_HELMET_I), item(RED_SLAYER_HELMET_I), item(TURQUOISE_SLAYER_HELMET_I))), new EmoteClue("Blow a raspberry at the monkey cage in Ardougne Zoo. Equip a studded leather body, bronze platelegs and a normal staff with no orb.", new WorldPoint(2607, 3282, 0), RASPBERRY, item(STUDDED_BODY), item(BRONZE_PLATELEGS), item(STAFF)), new EmoteClue("Blow raspberries outside the entrance to Keep Le Faye. Equip a coif, an iron platebody and leather gloves.", new WorldPoint(2757, 3401, 0), RASPBERRY, item(COIF), item(IRON_PLATEBODY), item(LEATHER_GLOVES)), new EmoteClue("Blow a raspberry in the Fishing Guild bank. Beware of double agents! Equip an elemental shield, blue dragonhide chaps and a rune warhammer.", new WorldPoint(2588, 3419, 0), RASPBERRY, item(ELEMENTAL_SHIELD), item(BLUE_DHIDE_CHAPS), item(RUNE_WARHAMMER)), new EmoteClue("Salute in the banana plantation. Beware of double agents! Equip a diamond ring, amulet of power, and nothing on your chest and legs.", new WorldPoint(2918, 3168, 0), SALUTE, item(DIAMOND_RING), item(AMULET_OF_POWER), emptySlot("Nothing on chest & legs", BODY, LEGS)), new EmoteClue("Salute in the Warriors' guild bank. Equip only a black salamander.", new WorldPoint(2844, 3542, 0), SALUTE, item(BLACK_SALAMANDER), emptySlot("Nothing else", HEAD, CAPE, AMULET, BODY, SHIELD, LEGS, GLOVES, BOOTS, RING)), new EmoteClue("Salute in the centre of the mess hall. Beware of double agents! Equip a rune halberd rune platebody, and an amulet of strength.", new WorldPoint(1646, 3632, 0), SALUTE, item(RUNE_HALBERD), item(RUNE_PLATEBODY), item(AMULET_OF_STRENGTH)), new EmoteClue("Shrug in the mine near Rimmington. Equip a gold necklace, a gold ring and a bronze spear.", new WorldPoint(2976, 3238, 0), SHRUG, item(GOLD_NECKLACE), item(GOLD_RING), item(BRONZE_SPEAR)), new EmoteClue("Shrug in Catherby bank. Yawn before you talk to me. Equip a maple longbow, green d'hide chaps and an iron med helm.", new WorldPoint(2808, 3440, 0), SHRUG, YAWN, item(MAPLE_LONGBOW), item(GREEN_DHIDE_CHAPS), item(IRON_MED_HELM)), new EmoteClue("Shrug in the Zamorak temple found in the Eastern Wilderness. Beware of double agents! Equip rune platelegs, an iron platebody and blue dragonhide vambraces.", new WorldPoint(3239, 3611, 0), SHRUG, item(RUNE_PLATELEGS), item(IRON_PLATEBODY), item(BLUE_DHIDE_VAMB)), new EmoteClue("Shrug in the Shayzien command tent. Equip a blue mystic robe bottom, a rune kiteshield and any bob shirt.", new WorldPoint(1555, 3537, 0), SHRUG, item(MYSTIC_ROBE_BOTTOM), item(RUNE_KITESHIELD), range("Any bob shirt", BOBS_RED_SHIRT, BOBS_PURPLE_SHIRT)), new EmoteClue("Slap your head in the centre of the Kourend catacombs. Beware of double agents! Equip the arclight and the amulet of the damned.", new WorldPoint(1663, 10045, 0), SLAP_HEAD, item(ARCLIGHT), item(AMULET_OF_THE_DAMNED)), new EmoteClue("Spin at the crossroads north of Rimmington. Equip a green gnome hat, cream gnome top and leather chaps.", new WorldPoint(2981, 3276, 0), SPIN, item(GREEN_HAT), item(CREAM_ROBE_TOP), item(LEATHER_CHAPS)), new EmoteClue("Spin in Draynor Manor by the fountain. Equip an iron platebody, studded leather chaps and a bronze full helmet.", new WorldPoint(3088, 3336, 0), SPIN, item(IRON_PLATELEGS), item(STUDDED_CHAPS), item(BRONZE_FULL_HELM)), new EmoteClue("Spin in front of the Soul altar. Beware of double agents! Equip a dragon pickaxe, helm of neitiznot and a pair of rune boots.", new WorldPoint(1815, 3856, 0), SPIN, item(DRAGON_PICKAXE), item(HELM_OF_NEITIZNOT), item(RUNE_BOOTS)), new EmoteClue("Spin in the Varrock Castle courtyard. Equip a black axe, a coif and a ruby ring.", new WorldPoint(3213, 3463, 0), SPIN, item(BLACK_AXE), item(COIF), item(RUBY_RING)), new EmoteClue("Spin in West Ardougne Church. Equip a dragon spear and red dragonhide chaps.", new WorldPoint(2404, 4326, 0), SPIN, item(DRAGON_SPEAR), item(RED_DHIDE_CHAPS)), new EmoteClue("Spin on the bridge by the Barbarian Village. Salute before you talk to me. Equip purple gloves, a steel kiteshield and a mithril full helmet.", new WorldPoint(3105, 3420, 0), SPIN, SALUTE, item(PURPLE_GLOVES), item(STEEL_KITESHIELD), item(MITHRIL_FULL_HELM)), new EmoteClue("Stamp in the Enchanted valley west of the waterfall. Beware of double agents! Equip a dragon axe.", new WorldPoint(3030, 4522, 0), STOMP, item(DRAGON_AXE)), new EmoteClue("Think in middle of the wheat field by the Lumbridge mill. Equip a blue gnome robetop, a turquoise gnome robe bottom and an oak shortbow.", new WorldPoint(3159, 3298, 0), THINK, item(BLUE_ROBE_TOP), item(TURQUOISE_ROBE_BOTTOMS), item(OAK_SHORTBOW)), new EmoteClue("Think in the centre of the Observatory. Spin before you talk to me. Equip a mithril chain body, green dragonhide chaps and a ruby amulet.", new WorldPoint(2439, 3161, 0), THINK, SPIN, item(MITHRIL_CHAINBODY), item(GREEN_DHIDE_CHAPS), item(RUBY_AMULET)), new EmoteClue("Wave along the south fence of the Lumber Yard. Equip a hard leather body, leather chaps and a bronze axe.", new WorldPoint(3307, 3491, 0), WAVE, item(HARDLEATHER_BODY), item(LEATHER_CHAPS), item(BRONZE_AXE)), new EmoteClue("Wave in the Falador gem store. Equip a Mithril pickaxe, Black platebody and an Iron Kiteshield.", new WorldPoint(2945, 3335, 0), WAVE, item(MITHRIL_PICKAXE), item(BLACK_PLATEBODY), item(IRON_KITESHIELD)), new EmoteClue("Wave on Mudskipper Point. Equip a black cape, leather chaps and a steel mace.", new WorldPoint(2989, 3110, 0), WAVE, item(BLACK_CAPE), item(LEATHER_CHAPS), item(STEEL_MACE)), new EmoteClue("Wave on the the nothern wall of Castle Drakan. Beware of double agents! Wear a dragon sq shield, splitbark body and any boater.", new WorldPoint(3560, 3385, 0), WAVE, item(DRAGON_SQ_SHIELD), item(SPLITBARK_BODY), any("Any boater", item(RED_BOATER), item(ORANGE_BOATER), item(GREEN_BOATER), item(BLUE_BOATER), item(BLACK_BOATER), item(PINK_BOATER), item(PURPLE_BOATER), item(WHITE_BOATER))), new EmoteClue("Yawn in the 7th room of Pyramid Plunder. Beware of double agents! Equip a pharoah sceptre and a full set of menaphite robes.", new WorldPoint(1944, 4427, 0), YAWN, item(PHARAOHS_SCEPTRE_3), item(MENAPHITE_PURPLE_HAT), item(MENAPHITE_PURPLE_TOP), item(MENAPHITE_PURPLE_ROBE)), new EmoteClue("Yawn in the Varrock library. Equip a green gnome robe top, HAM robe bottom and an iron warhammer.", new WorldPoint(3209, 3492, 0), YAWN, item(GREEN_ROBE_TOP), item(HAM_ROBE), item(IRON_WARHAMMER)), new EmoteClue("Yawn in Draynor Marketplace. Equip studded leather chaps, an iron kiteshield and a steel longsword.", new WorldPoint(3083, 3253, 0), YAWN, item(STUDDED_CHAPS), item(IRON_KITESHIELD), item(STEEL_LONGSWORD)), new EmoteClue("Yawn in the Castle Wars lobby. Shrug before you talk to me. Equip a ruby amulet, a mithril scimitar and a Wilderness cape.", new WorldPoint(2440, 3092, 0), YAWN, SHRUG, item(RUBY_AMULET), item(MITHRIL_SCIMITAR), range("Any team cape", TEAM1_CAPE, TEAM50_CAPE)), new EmoteClue("Yawn in the rogues' general store. Beware of double agents! Equip an adamant square shield, blue dragon vambraces and a rune pickaxe.", new WorldPoint(3026, 3701, 0), YAWN, item(ADAMANT_SQ_SHIELD), item(BLUE_DHIDE_VAMB), item(RUNE_PICKAXE)), new EmoteClue("Yawn at the top of Trollheim. Equip a lava battlestaff, black dragonhide vambraces and a mind shield.", new WorldPoint(2590, 4452, 0), YAWN, item(LAVA_BATTLESTAFF), item(BLACK_DHIDE_VAMB), item(MIND_SHIELD)), new EmoteClue("Yawn in the centre of Arceuus library. Nod your head before you talk to me. Equip blue dragonhide vambraces, adamant boots and an adamant dagger.", new WorldPoint(1632, 3807, 0), YAWN, YES, item(BLUE_DHIDE_VAMB), item(ADAMANT_BOOTS), item(ADAMANT_DAGGER)), new EmoteClue("Swing a bullroarer at the top of the watchtower. Beware of double agents! Equip a dragon plateskirt, climbing boots and a dragon chainbody.", new WorldPoint(2932, 4712, 0), BULL_ROARER, item(DRAGON_PLATESKIRT), item(CLIMBING_BOOTS), item(DRAGON_CHAINBODY_3140)) ); private static SingleItemRequirement item(int itemId) { return new SingleItemRequirement(itemId); } private static RangeItemRequirement range(int startItemId, int endItemId) { return range(null, startItemId, endItemId); } private static RangeItemRequirement range(String name, int startItemId, int endItemId) { return new RangeItemRequirement(name, startItemId, endItemId); } private static AnyRequirementCollection any(String name, ItemRequirement... requirements) { return new AnyRequirementCollection(name, requirements); } private static AllRequirementsCollection all(ItemRequirement... requirements) { return new AllRequirementsCollection(requirements); } private static SlotLimitationRequirement emptySlot(String description, EquipmentInventorySlot... slots) { return new SlotLimitationRequirement(description, slots); } private String text; private WorldPoint location; private Emote firstEmote; private Emote secondEmote; private ItemRequirement[] itemRequirements; private EmoteClue(String text, WorldPoint location, Emote firstEmote, ItemRequirement... itemRequirements) { this(text, location, firstEmote, null, itemRequirements); } private EmoteClue(String text, WorldPoint location, Emote firstEmote, Emote secondEmote, ItemRequirement... itemRequirements) { this.text = text; this.location = location; this.firstEmote = firstEmote; this.secondEmote = secondEmote; this.itemRequirements = itemRequirements; } @Override public void makeOverlayHint(PanelComponent panelComponent, ClueScrollPlugin plugin) { panelComponent.getChildren().add(TitleComponent.builder().text("Emote Clue").build()); panelComponent.getChildren().add(LineComponent.builder().left("Emotes:").build()); panelComponent.getChildren().add(LineComponent.builder() .left(getFirstEmote().getName()) .leftColor(TITLED_CONTENT_COLOR) .build()); if (getSecondEmote() != null) { panelComponent.getChildren().add(LineComponent.builder() .left(getSecondEmote().getName()) .leftColor(TITLED_CONTENT_COLOR) .build()); } if (getItemRequirements() == null) { panelComponent.getChildren().add(LineComponent.builder() .left("Items:") .right("None") .build()); } else { panelComponent.getChildren().add(LineComponent.builder().left("Equip:").build()); Item[] items = plugin.getEquippedItems(); // If items is null, the player is wearing nothing if (items == null) { items = new Item[0]; } for (ItemRequirement requirement : getItemRequirements()) { boolean found = requirement.fulfilledBy(items); panelComponent.getChildren().add(LineComponent.builder() .left(requirement.getCollectiveName(plugin.getClient())) .leftColor(TITLED_CONTENT_COLOR) .right(found ? "X" : "-") .rightColor(found ? Color.GREEN : Color.RED) .build()); } } } @Override public void makeWorldOverlayHint(Graphics2D graphics, ClueScrollPlugin plugin) { LocalPoint localLocation = LocalPoint.fromWorld(plugin.getClient(), getLocation()); if (localLocation == null) { return; } OverlayUtil.renderTileOverlay(plugin.getClient(), graphics, localLocation, EMOTE_IMAGE, Color.ORANGE); } public static EmoteClue forText(String text) { for (EmoteClue clue : CLUES) { if (clue.getText().equalsIgnoreCase(text)) { return clue; } } return null; } }
package net.runelite.client.plugins.worldmap; import lombok.Getter; import net.runelite.api.coords.WorldPoint; import net.runelite.api.Quest; // Some quests are in the same spot, but they are done in order. If multiple // quests start in the same location, an array of quests is expected. enum QuestStartLocation { //Free Quests COOKS_ASSISTANT_RFD(Quest.COOKS_ASSISTANT, new WorldPoint(3211, 3216, 0)), THE_CORSAIR_CURSE(Quest.THE_CORSAIR_CURSE, new WorldPoint(3029, 3273, 0)), DEMON_SLAYER(Quest.DEMON_SLAYER, new WorldPoint(3204, 3424, 0)), DORICS_QUEST(Quest.DORICS_QUEST, new WorldPoint(2952, 3450, 0)), DRAGON_SLAYER(Quest.DRAGON_SLAYER, new WorldPoint(3190, 3362, 0)), ERNEST_THE_CHICKEN(Quest.ERNEST_THE_CHICKEN, new WorldPoint(3109, 3330, 0)), GOBLIN_DIPLOMACY(Quest.GOBLIN_DIPLOMACY, new WorldPoint(2957, 3509, 0)), IMP_CATCHER(Quest.IMP_CATCHER, new WorldPoint(3108, 3160, 0)), THE_KNIGHTS_SWORD(Quest.THE_KNIGHTS_SWORD, new WorldPoint(2976, 3342, 0)), MISTHALIN_MYSTERY(Quest.MISTHALIN_MYSTERY, new WorldPoint(3235, 3155, 0)), PIRATES_TREASURE(Quest.PIRATES_TREASURE, new WorldPoint(3051, 3252, 0)), PRINCE_ALI_RESCUE(Quest.PRINCE_ALI_RESCUE, new WorldPoint(3301, 3163, 0)), THE_RESTLESS_GHOST(Quest.THE_RESTLESS_GHOST, new WorldPoint(3240, 3210, 0)), RUNE_MYSTERIES(Quest.RUNE_MYSTERIES, new WorldPoint(3210, 3220, 0)), SHEEP_SHEARER(Quest.SHEEP_SHEARER, new WorldPoint(3190, 3272, 0)), SHIELD_OF_ARRAV_PHOENIX_GANG(Quest.SHIELD_OF_ARRAV, new WorldPoint(3208, 3495, 0)), SHIELD_OF_ARRAV_BLACK_ARM_GANG(Quest.SHIELD_OF_ARRAV, new WorldPoint(3208, 3392, 0)), VAMPYRE_SLAYER(Quest.VAMPYRE_SLAYER, new WorldPoint(3096, 3266, 0)), WITCHS_POTION(Quest.WITCHS_POTION, new WorldPoint(2967, 3203, 0)), X_MARKS_THE_SPOT(Quest.X_MARKS_THE_SPOT, new WorldPoint(3227, 3242, 0)), //Members' Quests ANIMAL_MAGNETISM(Quest.ANIMAL_MAGNETISM, new WorldPoint(3094, 3360, 0)), ANOTHER_SLICE_OF_HAM(Quest.ANOTHER_SLICE_OF_HAM, new WorldPoint(2799, 5428, 0)), THE_ASCENT_OF_ARCEUUS(Quest.THE_ASCENT_OF_ARCEUUS, new WorldPoint(1699, 3742, 0)), BETWEEN_A_ROCK(Quest.BETWEEN_A_ROCK, new WorldPoint(2823, 10168, 0)), BIG_CHOMPY_BIRD_HUNTING(Quest.BIG_CHOMPY_BIRD_HUNTING, new WorldPoint(2629, 2981, 0)), BIOHAZARD(Quest.BIOHAZARD, new WorldPoint(2591, 3335, 0)), BONE_VOYAGE(Quest.BONE_VOYAGE, new WorldPoint(3259, 3450, 0)), CABIN_FEVER(Quest.CABIN_FEVER, new WorldPoint(3674, 3496, 0)), CLIENT_OF_KOUREND(Quest.CLIENT_OF_KOUREND, new WorldPoint(1823, 3690, 0)), CLOCK_TOWER(Quest.CLOCK_TOWER, new WorldPoint(2568, 3249, 0)), COLD_WAR(Quest.COLD_WAR, new WorldPoint(2593, 3265, 0)), CONTACT(Quest.CONTACT, new WorldPoint(3280, 2770, 0)), CREATURE_OF_FENKENSTRAIN(Quest.CREATURE_OF_FENKENSTRAIN, new WorldPoint(3487, 3485, 0)), DARKNESS_OF_HALLOWVALE(Quest.DARKNESS_OF_HALLOWVALE, new WorldPoint(3494, 9628, 0)), DEATH_PLATEAU_TROLL_STRONGHOLD(new Quest[]{Quest.DEATH_PLATEAU, Quest.TROLL_STRONGHOLD}, new WorldPoint(2895, 3528, 0)), DEATH_TO_THE_DORGESHUUN(Quest.DEATH_TO_THE_DORGESHUUN, new WorldPoint(3316, 9613, 0)), THE_DEPTHS_OF_DESPAIR(Quest.THE_DEPTHS_OF_DESPAIR, new WorldPoint(1781, 3570, 0)), DESERT_TREASURE(Quest.DESERT_TREASURE, new WorldPoint(3177, 3043, 0)), DEVIOUS_MINDS(Quest.DEVIOUS_MINDS, new WorldPoint(3405, 3492, 0)), THE_DIG_SITE(Quest.THE_DIG_SITE, new WorldPoint(3363, 3337, 0)), DRAGON_SLAYER_II(Quest.DRAGON_SLAYER_II, new WorldPoint(2456, 2868, 0)), DREAM_MENTOR(Quest.DREAM_MENTOR, new WorldPoint(2144, 10346, 0)), DRUIDIC_RITUAL(Quest.DRUIDIC_RITUAL, new WorldPoint(2916, 3484, 0)), DWARF_CANNON(Quest.DWARF_CANNON, new WorldPoint(2566, 3461, 0)), EADGARS_RUSE(Quest.EADGARS_RUSE, new WorldPoint(2896, 3426, 0)), EAGLES_PEAK(Quest.EAGLES_PEAK, new WorldPoint(2605, 3264, 0)), ELEMENTAL_WORKSHOP(new Quest[]{Quest.ELEMENTAL_WORKSHOP_I, Quest.ELEMENTAL_WORKSHOP_II}, new WorldPoint(2714, 3482, 0)), ENAKHRAS_LAMENT(Quest.ENAKHRAS_LAMENT, new WorldPoint(3190, 2926, 0)), ENLIGHTENED_JOURNEY(Quest.ENLIGHTENED_JOURNEY, new WorldPoint(2809, 3356, 0)), THE_EYES_OF_GLOUPHRIE(Quest.THE_EYES_OF_GLOUPHRIE, new WorldPoint(2400, 3419, 0)), FAIRYTALE(new Quest[]{Quest.FAIRYTALE_I__GROWING_PAINS, Quest.FAIRYTALE_II__CURE_A_QUEEN}, new WorldPoint(3077, 3258, 0)), FAMILY_CREST(Quest.FAMILY_CREST, new WorldPoint(3278, 3404, 0)), THE_FEUD(Quest.THE_FEUD, new WorldPoint(3301, 3211, 0)), FIGHT_ARENA(Quest.FIGHT_ARENA, new WorldPoint(2565, 3199, 0)), FISHING_CONTEST_1(Quest.FISHING_CONTEST, new WorldPoint(2875, 3483, 0)), FISHING_CONTEST_2(Quest.FISHING_CONTEST, new WorldPoint(2820, 3487, 0)), FORGETTABLE_TALE(Quest.FORGETTABLE_TALE, new WorldPoint(2826, 10215, 0)), THE_FORSAKEN_TOWER(Quest.THE_FORSAKEN_TOWER, new WorldPoint(1482, 3748, 0)), THE_FREMENNIK_ISLES(Quest.THE_FREMENNIK_ISLES, new WorldPoint(2645, 3711, 0)), THE_FREMENNIK_TRIALS(Quest.THE_FREMENNIK_TRIALS, new WorldPoint(2657, 3669, 0)), THE_FREMENNIK_EXILES(Quest.THE_FREMENNIK_EXILES, new WorldPoint(2658, 3669, 0)), GARDEN_OF_TRANQUILLITY(Quest.GARDEN_OF_TRANQUILLITY, new WorldPoint(3227, 3477, 0)), GERTRUDES_CAT_RATCATCHERS(Quest.GERTRUDES_CAT, new WorldPoint(3150, 3411, 0)), GHOSTS_AHOY(Quest.GHOSTS_AHOY, new WorldPoint(3677, 3510, 0)), THE_GIANT_DWARF(Quest.THE_GIANT_DWARF, new WorldPoint(2841, 10129, 0)), THE_GOLEM(Quest.THE_GOLEM, new WorldPoint(3487, 3089, 0)), THE_GRAND_TREE_MONKEY_MADNESS(new Quest[]{Quest.THE_GRAND_TREE, Quest.MONKEY_MADNESS_I, Quest.MONKEY_MADNESS_II}, new WorldPoint(2466, 3497, 0)), THE_GREAT_BRAIN_ROBBERY(Quest.THE_GREAT_BRAIN_ROBBERY, new WorldPoint(3681, 2963, 0)), GRIM_TALES(Quest.GRIM_TALES, new WorldPoint(2890, 3454, 0)), THE_HAND_IN_THE_SAND(Quest.THE_HAND_IN_THE_SAND, new WorldPoint(2552, 3101, 0)), HAUNTED_MINE(Quest.HAUNTED_MINE, new WorldPoint(3443, 3258, 0)), HAZEEL_CULT(Quest.HAZEEL_CULT, new WorldPoint(2565, 3271, 0)), HEROES_QUEST(Quest.HEROES_QUEST, new WorldPoint(2903, 3511, 0)), HOLY_GRAIL(new Quest[]{Quest.MERLINS_CRYSTAL, Quest.HOLY_GRAIL}, new WorldPoint(2763, 3515, 0)), HORROR_FROM_THE_DEEP(Quest.HORROR_FROM_THE_DEEP, new WorldPoint(2507, 3635, 0)), ICTHLARINS_LITTLE_HELPER(Quest.ICTHLARINS_LITTLE_HELPER, new WorldPoint(3314, 2849, 0)), IN_SEARCH_OF_THE_MYREQUE(Quest.IN_SEARCH_OF_THE_MYREQUE, new WorldPoint(3502, 3477, 0)), JUNGLE_POTION(Quest.JUNGLE_POTION, new WorldPoint(2809, 3086, 0)), KINGS_RANSOM(Quest.KINGS_RANSOM, new WorldPoint(2741, 3554, 0)), LEGENDS_QUEST(Quest.LEGENDS_QUEST, new WorldPoint(2725, 3367, 0)), LOST_CITY(Quest.LOST_CITY, new WorldPoint(3149, 3205, 0)), THE_LOST_TRIBE(Quest.THE_LOST_TRIBE, new WorldPoint(3211, 3224, 0)), LUNAR_DIPLOMACY(Quest.LUNAR_DIPLOMACY, new WorldPoint(2618, 3691, 0)), MAKING_FRIENDS_WITH_MY_ARM(Quest.MAKING_FRIENDS_WITH_MY_ARM, new WorldPoint(2904, 10092, 0)), MAKING_HISTORY(Quest.MAKING_HISTORY, new WorldPoint(2435, 3346, 0)), MONKS_FRIEND(Quest.MONKS_FRIEND, new WorldPoint(2605, 3209, 0)), MOUNTAIN_DAUGHTER(Quest.MOUNTAIN_DAUGHTER, new WorldPoint(2810, 3672, 0)), MOURNINGS_ENDS_PART_I(Quest.MOURNINGS_END_PART_I, new WorldPoint(2289, 3149, 0)), MOURNINGS_ENDS_PART_II(Quest.MOURNINGS_END_PART_II, new WorldPoint(2352, 3172, 0)), MURDER_MYSTERY(Quest.MURDER_MYSTERY, new WorldPoint(2740, 3562, 0)), MY_ARMS_BIG_ADVENTURE(Quest.MY_ARMS_BIG_ADVENTURE, new WorldPoint(2908, 10088, 0)), NATURE_SPIRIT(Quest.NATURE_SPIRIT, new WorldPoint(3440, 9894, 0)), OBSERVATORY_QUEST(Quest.OBSERVATORY_QUEST, new WorldPoint(2438, 3185, 0)), OLAFS_QUEST(Quest.OLAFS_QUEST, new WorldPoint(2723, 3729, 0)), ONE_SMALL_FAVOUR(Quest.ONE_SMALL_FAVOUR, new WorldPoint(2834, 2985, 0)), PLAGUE_CITY_SONG_OF_THE_ELVES(new Quest[]{Quest.PLAGUE_CITY, Quest.SONG_OF_THE_ELVES}, new WorldPoint(2567, 3334, 0)), A_PORCINE_OF_INTEREST(Quest.A_PORCINE_OF_INTEREST, new WorldPoint(3085, 3251, 0)), PRIEST_IN_PERIL(Quest.PRIEST_IN_PERIL, new WorldPoint(3219, 3473, 0)), THE_QUEEN_OF_THIEVES(Quest.THE_QUEEN_OF_THIEVES, new WorldPoint(1795, 3782, 0)), RAG_AND_BONE_MAN(new Quest[]{Quest.RAG_AND_BONE_MAN, Quest.RAG_AND_BONE_MAN_II}, new WorldPoint(3359, 3504, 0)), RECRUITMENT_DRIVE_BLACK_KNIGHTS_FORTRESS(new Quest[]{Quest.BLACK_KNIGHTS_FORTRESS, Quest.RECRUITMENT_DRIVE}, new WorldPoint(2959, 3336, 0)), ROVING_ELVES(Quest.ROVING_ELVES, new WorldPoint(2288, 3146, 0)), RUM_DEAL(Quest.RUM_DEAL, new WorldPoint(3679, 3535, 0)), SCORPION_CATCHER(Quest.SCORPION_CATCHER, new WorldPoint(2701, 3399, 0)), SEA_SLUG(Quest.SEA_SLUG, new WorldPoint(2715, 3302, 0)), SHADES_OF_MORTTON(Quest.SHADES_OF_MORTTON, new WorldPoint(3463, 3308, 0)), SHADOW_OF_THE_STORM(Quest.SHADOW_OF_THE_STORM, new WorldPoint(3270, 3159, 0)), SHEEP_HERDER(Quest.SHEEP_HERDER, new WorldPoint(2616, 3299, 0)), SHILO_VILLAGE(Quest.SHILO_VILLAGE, new WorldPoint(2882, 2951, 0)), SINS_OF_THE_FATHER(Quest.SINS_OF_THE_FATHER, new WorldPoint(3728, 3319, 0)), A_SOULS_BANE(Quest.A_SOULS_BANE, new WorldPoint(3307, 3454, 0)), SPIRITS_OF_THE_ELID(Quest.SPIRITS_OF_THE_ELID, new WorldPoint(3441, 2911, 0)), SWAN_SONG(Quest.SWAN_SONG, new WorldPoint(2345, 3652, 0)), TAI_BWO_WANNAI_TRIO(Quest.TAI_BWO_WANNAI_TRIO, new WorldPoint(2779, 3087, 0)), A_TAIL_OF_TWO_CATS(Quest.A_TAIL_OF_TWO_CATS, new WorldPoint(2917, 3557, 0)), TALE_OF_THE_RIGHTEOUS(Quest.TALE_OF_THE_RIGHTEOUS, new WorldPoint(1511, 3631, 0)), A_TASTE_OF_HOPE(Quest.A_TASTE_OF_HOPE, new WorldPoint(3668, 3216, 0)), TEARS_OF_GUTHIX(Quest.TEARS_OF_GUTHIX, new WorldPoint(3251, 9517, 0)), TEMPLE_OF_IKOV(Quest.TEMPLE_OF_IKOV, new WorldPoint(2574, 3320, 0)), THRONE_OF_MISCELLANIA_ROYAL_TROUBLE(new Quest[]{Quest.THRONE_OF_MISCELLANIA, Quest.ROYAL_TROUBLE}, new WorldPoint(2497, 3859, 0)), THE_TOURIST_TRAP(Quest.THE_TOURIST_TRAP, new WorldPoint(3302, 3113, 0)), TOWER_OF_LIFE(Quest.TOWER_OF_LIFE, new WorldPoint(2640, 3218, 0)), TREE_GNOME_VILLAGE(Quest.TREE_GNOME_VILLAGE, new WorldPoint(2541, 3169, 0)), TRIBAL_TOTEM(Quest.TRIBAL_TOTEM, new WorldPoint(2790, 3182, 0)), TROLL_ROMANCE(Quest.TROLL_ROMANCE, new WorldPoint(2890, 10097, 0)), UNDERGROUND_PASS_REGICIDE(new Quest[]{Quest.REGICIDE, Quest.UNDERGROUND_PASS}, new WorldPoint(2575, 3293, 0)), WANTED_SLUG_MENACE(new Quest[]{Quest.WANTED, Quest.THE_SLUG_MENACE}, new WorldPoint(2996, 3373, 0)), WATCHTOWER(Quest.WATCHTOWER, new WorldPoint(2545, 3112, 0)), WATERFALL_QUEST(Quest.WATERFALL_QUEST, new WorldPoint(2521, 3498, 0)), WHAT_LIES_BELOW(Quest.WHAT_LIES_BELOW, new WorldPoint(3265, 3333, 0)), WITCHS_HOUSE(Quest.WITCHS_HOUSE, new WorldPoint(2927, 3456, 0)), ZOGRE_FLESH_EATERS(Quest.ZOGRE_FLESH_EATERS, new WorldPoint(2442, 3051, 0)); @Getter private final WorldPoint location; @Getter private final Quest[] quests; QuestStartLocation(Quest[] quests, WorldPoint location) { this.location = location; this.quests = quests; } QuestStartLocation(Quest quest, WorldPoint location) { this.location = location; this.quests = new Quest[]{quest}; } }
package com.smartdevicelink.api.audio; import android.content.Context; import android.media.AudioFormat; import android.media.MediaFormat; import android.media.MediaPlayer; import android.os.Build; import android.os.Environment; import android.support.test.InstrumentationRegistry; import android.util.Log; import com.smartdevicelink.SdlConnection.SdlSession; import com.smartdevicelink.api.CompletionListener; import com.smartdevicelink.protocol.enums.SessionType; import com.smartdevicelink.proxy.interfaces.IAudioStreamListener; import com.smartdevicelink.proxy.interfaces.ISdl; import com.smartdevicelink.api.audio.AudioStreamManager.SampleType; import com.smartdevicelink.proxy.interfaces.ISdlServiceListener; import com.smartdevicelink.proxy.rpc.AudioPassThruCapabilities; import com.smartdevicelink.proxy.rpc.enums.AudioType; import com.smartdevicelink.proxy.rpc.enums.BitsPerSample; import com.smartdevicelink.proxy.rpc.enums.SamplingRate; import com.smartdevicelink.proxy.rpc.enums.SystemCapabilityType; import junit.framework.TestCase; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.RandomAccessFile; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.nio.ByteOrder; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; public class AudioStreamManagerTest extends TestCase { public static final String TAG = AudioStreamManagerTest.class.getSimpleName(); private Context mContext; @Override public void setUp() throws Exception { super.setUp(); mContext = InstrumentationRegistry.getContext(); } @Override public void tearDown() throws Exception { super.tearDown(); mContext = null; } public void testCreatingAudioStreamManager() { ISdl internalInterface = mock(ISdl.class); AudioPassThruCapabilities audioCapabilities = new AudioPassThruCapabilities(SamplingRate._16KHZ, BitsPerSample._16_BIT, AudioType.PCM); doReturn(true).when(internalInterface).isConnected(); doReturn(audioCapabilities).when(internalInterface).getCapability(SystemCapabilityType.PCM_STREAMING); new AudioStreamManager(internalInterface, mContext); } public void testStartAudioStreamManager() { final SdlSession mockSession = mock(SdlSession.class); Answer<Void> audioServiceAnswer = new Answer<Void>() { ISdlServiceListener serviceListener = null; @Override public Void answer(InvocationOnMock invocation) { Method method = invocation.getMethod(); Object[] args = invocation.getArguments(); switch (method.getName()) { case "addServiceListener": // parameters (SessionType serviceType, ISdlServiceListener sdlServiceListener); SessionType sessionType = (SessionType) args[0]; assertEquals(sessionType, SessionType.PCM); serviceListener = (ISdlServiceListener) args[1]; break; case "startAudioService": // parameters (boolean encrypted, AudioStreamingCodec codec, AudioStreamingParams params); Boolean encrypted = (Boolean) args[0]; serviceListener.onServiceStarted(mockSession, SessionType.PCM, encrypted); break; case "stopAudioService": // parameters () serviceListener.onServiceEnded(mockSession, SessionType.PCM); break; } return null; } }; ISdl internalInterface = mock(ISdl.class); AudioPassThruCapabilities audioCapabilities = new AudioPassThruCapabilities(SamplingRate._16KHZ, BitsPerSample._16_BIT, AudioType.PCM); doReturn(true).when(internalInterface).isConnected(); doReturn(audioCapabilities).when(internalInterface).getCapability(SystemCapabilityType.PCM_STREAMING); doAnswer(audioServiceAnswer).when(internalInterface).addServiceListener(any(SessionType.class), any(ISdlServiceListener.class)); doAnswer(audioServiceAnswer).when(internalInterface).startAudioService(any(Boolean.class)); doAnswer(audioServiceAnswer).when(internalInterface).stopAudioService(); CompletionListener completionListener = new CompletionListener() { @Override public void onComplete(boolean success) { assertEquals(true, success); } }; CompletionListener mockListener = spy(completionListener); AudioStreamManager manager = new AudioStreamManager(internalInterface, mContext); manager.startAudioStream(false, mockListener); manager.stopAudioStream(mockListener); verify(mockListener, timeout(10000).times(2)).onComplete(any(Boolean.class)); } public void testWithSquareSampleAudio16BitAnd8KhzApi16() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 16); AudioPassThruCapabilities audioPassThruCapabilities = new AudioPassThruCapabilities(SamplingRate._8KHZ, BitsPerSample._16_BIT, AudioType.PCM); runFullAudioManagerDecodeFlowWithSquareSampleAudio(8000, SampleType.SIGNED_16_BIT, audioPassThruCapabilities); } public void testWithSquareSampleAudio16BitAnd16KhzApi16() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 16); AudioPassThruCapabilities audioPassThruCapabilities = new AudioPassThruCapabilities(SamplingRate._16KHZ, BitsPerSample._16_BIT, AudioType.PCM); runFullAudioManagerDecodeFlowWithSquareSampleAudio(16000, SampleType.SIGNED_16_BIT, audioPassThruCapabilities); } public void testWithSquareSampleAudio16BitAnd22KhzApi16() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 16); AudioPassThruCapabilities audioPassThruCapabilities = new AudioPassThruCapabilities(SamplingRate._22KHZ, BitsPerSample._16_BIT, AudioType.PCM); runFullAudioManagerDecodeFlowWithSquareSampleAudio(22050, SampleType.SIGNED_16_BIT, audioPassThruCapabilities); } public void testWithSquareSampleAudio16BitAnd44KhzApi16() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 16); AudioPassThruCapabilities audioPassThruCapabilities = new AudioPassThruCapabilities(SamplingRate._44KHZ, BitsPerSample._16_BIT, AudioType.PCM); runFullAudioManagerDecodeFlowWithSquareSampleAudio(44100, SampleType.SIGNED_16_BIT, audioPassThruCapabilities); } public void testWithSquareSampleAudio8BitAnd8KhzApi16() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 16); AudioPassThruCapabilities audioPassThruCapabilities = new AudioPassThruCapabilities(SamplingRate._8KHZ, BitsPerSample._8_BIT, AudioType.PCM); runFullAudioManagerDecodeFlowWithSquareSampleAudio(8000, SampleType.UNSIGNED_8_BIT, audioPassThruCapabilities); } public void testWithSquareSampleAudio8BitAnd16KhzApi16() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 16); AudioPassThruCapabilities audioPassThruCapabilities = new AudioPassThruCapabilities(SamplingRate._16KHZ, BitsPerSample._8_BIT, AudioType.PCM); runFullAudioManagerDecodeFlowWithSquareSampleAudio(16000, SampleType.UNSIGNED_8_BIT, audioPassThruCapabilities); } public void testWithSquareSampleAudio8BitAnd22KhzApi16() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 16); AudioPassThruCapabilities audioPassThruCapabilities = new AudioPassThruCapabilities(SamplingRate._22KHZ, BitsPerSample._8_BIT, AudioType.PCM); runFullAudioManagerDecodeFlowWithSquareSampleAudio(22050, SampleType.UNSIGNED_8_BIT, audioPassThruCapabilities); } public void testWithSquareSampleAudio8BitAnd44KhzApi16() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 16); AudioPassThruCapabilities audioPassThruCapabilities = new AudioPassThruCapabilities(SamplingRate._44KHZ, BitsPerSample._8_BIT, AudioType.PCM); runFullAudioManagerDecodeFlowWithSquareSampleAudio(44100, SampleType.UNSIGNED_8_BIT, audioPassThruCapabilities); } public void testWithSquareSampleAudio16BitAnd8KhzApi21() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 21); AudioPassThruCapabilities audioPassThruCapabilities = new AudioPassThruCapabilities(SamplingRate._8KHZ, BitsPerSample._16_BIT, AudioType.PCM); runFullAudioManagerDecodeFlowWithSquareSampleAudio(8000, SampleType.SIGNED_16_BIT, audioPassThruCapabilities); } public void testWithSquareSampleAudio16BitAnd16KhzApi21() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 21); AudioPassThruCapabilities audioPassThruCapabilities = new AudioPassThruCapabilities(SamplingRate._16KHZ, BitsPerSample._16_BIT, AudioType.PCM); runFullAudioManagerDecodeFlowWithSquareSampleAudio(16000, SampleType.SIGNED_16_BIT, audioPassThruCapabilities); } public void testWithSquareSampleAudio16BitAnd22KhzApi21() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 21); AudioPassThruCapabilities audioPassThruCapabilities = new AudioPassThruCapabilities(SamplingRate._22KHZ, BitsPerSample._16_BIT, AudioType.PCM); runFullAudioManagerDecodeFlowWithSquareSampleAudio(22050, SampleType.SIGNED_16_BIT, audioPassThruCapabilities); } public void testWithSquareSampleAudio16BitAnd44KhzApi21() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 21); AudioPassThruCapabilities audioPassThruCapabilities = new AudioPassThruCapabilities(SamplingRate._44KHZ, BitsPerSample._16_BIT, AudioType.PCM); runFullAudioManagerDecodeFlowWithSquareSampleAudio(44100, SampleType.SIGNED_16_BIT, audioPassThruCapabilities); } public void testWithSquareSampleAudio8BitAnd8KhzApi21() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 21); AudioPassThruCapabilities audioPassThruCapabilities = new AudioPassThruCapabilities(SamplingRate._8KHZ, BitsPerSample._8_BIT, AudioType.PCM); runFullAudioManagerDecodeFlowWithSquareSampleAudio(8000, SampleType.UNSIGNED_8_BIT, audioPassThruCapabilities); } public void testWithSquareSampleAudio8BitAnd16KhzApi21() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 21); AudioPassThruCapabilities audioPassThruCapabilities = new AudioPassThruCapabilities(SamplingRate._16KHZ, BitsPerSample._8_BIT, AudioType.PCM); runFullAudioManagerDecodeFlowWithSquareSampleAudio(16000, SampleType.UNSIGNED_8_BIT, audioPassThruCapabilities); } public void testWithSquareSampleAudio8BitAnd22KhzApi21() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 21); AudioPassThruCapabilities audioPassThruCapabilities = new AudioPassThruCapabilities(SamplingRate._22KHZ, BitsPerSample._8_BIT, AudioType.PCM); runFullAudioManagerDecodeFlowWithSquareSampleAudio(22050, SampleType.UNSIGNED_8_BIT, audioPassThruCapabilities); } public void testWithSquareSampleAudio8BitAnd44KhzApi21() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 21); AudioPassThruCapabilities audioPassThruCapabilities = new AudioPassThruCapabilities(SamplingRate._44KHZ, BitsPerSample._8_BIT, AudioType.PCM); runFullAudioManagerDecodeFlowWithSquareSampleAudio(44100, SampleType.UNSIGNED_8_BIT, audioPassThruCapabilities); } private int testFullAudioManagerDecodeFlowCorrectCounter = 0; private int testFullAudioManagerDecodeFlowWrongCounter = 0; private void runFullAudioManagerDecodeFlowWithSquareSampleAudio(final int sampleRate, final @SampleType int sampleType, final AudioPassThruCapabilities audioCapabilities) { testFullAudioManagerDecodeFlowCorrectCounter = 0; testFullAudioManagerDecodeFlowWrongCounter = 0; IAudioStreamListener audioStreamListener = new IAudioStreamListener() { @Override public void sendAudio(byte[] data, int offset, int length, long presentationTimeUs) throws ArrayIndexOutOfBoundsException { ByteBuffer buffer = ByteBuffer.wrap(data, offset, length); this.sendAudio(buffer, presentationTimeUs); } @Override public void sendAudio(ByteBuffer data, long presentationTimeUs) { SampleBuffer samples = SampleBuffer.wrap(data, sampleType, presentationTimeUs); double timeUs = presentationTimeUs; double sampleDurationUs = 1000000.0 / sampleRate; for (int i = 0; i < samples.limit(); ++i) { double sample = samples.get(i); double edge = timeUs % 4000.0; if (edge > 2000.0) { // swap sample as it's negative expected sample = sample * -1.0; } edge = edge % 2000.0; // at the edge of a wave the sample can be lower than 0.7 if ((sample > 0.7 && sample < 0.95) || (edge < sampleDurationUs || (2000.0 - sampleDurationUs) < edge)) { testFullAudioManagerDecodeFlowCorrectCounter++; } else { testFullAudioManagerDecodeFlowWrongCounter++; } timeUs += sampleDurationUs; } } }; final SdlSession mockSession = mock(SdlSession.class); doReturn(audioStreamListener).when(mockSession).startAudioStream(); Answer<Void> audioServiceAnswer = new Answer<Void>() { ISdlServiceListener serviceListener = null; @Override public Void answer(InvocationOnMock invocation) { Method method = invocation.getMethod(); Object[] args = invocation.getArguments(); switch (method.getName()) { case "addServiceListener": // (SessionType serviceType, ISdlServiceListener sdlServiceListener); SessionType sessionType = (SessionType) args[0]; assertEquals(sessionType, SessionType.PCM); serviceListener = (ISdlServiceListener) args[1]; break; case "startAudioService": //(boolean encrypted, AudioStreamingCodec codec, AudioStreamingParams params); Boolean encrypted = (Boolean) args[0]; serviceListener.onServiceStarted(mockSession, SessionType.PCM, encrypted); break; case "stopAudioService": // parameters () serviceListener.onServiceEnded(mockSession, SessionType.PCM); break; } return null; } }; ISdl internalInterface = mock(ISdl.class); doReturn(true).when(internalInterface).isConnected(); doReturn(audioCapabilities).when(internalInterface).getCapability(any(SystemCapabilityType.class)); doAnswer(audioServiceAnswer).when(internalInterface).addServiceListener(any(SessionType.class), any(ISdlServiceListener.class)); doAnswer(audioServiceAnswer).when(internalInterface).startAudioService(any(Boolean.class)); doAnswer(audioServiceAnswer).when(internalInterface).stopAudioService(); CompletionListener fileCompletionListener = new CompletionListener() { @Override public void onComplete(boolean success) { assertEquals(true, success); // not more than 2.5 percent samples must be wrong double relation = 100.0 * (double)testFullAudioManagerDecodeFlowWrongCounter / (double)testFullAudioManagerDecodeFlowCorrectCounter; Log.v(TAG, "Validating number of correct samples (" + Math.round(relation) + "%)"); if (relation > 2.5) { fail("Validating raw audio failed. " + Math.round(relation) + " % wrong samples detected. Correct: " + testFullAudioManagerDecodeFlowCorrectCounter + ", Wrong: " + testFullAudioManagerDecodeFlowWrongCounter); } } }; final CompletionListener mockFileListener = spy(fileCompletionListener); final AudioStreamManager manager = new AudioStreamManager(internalInterface, mContext); manager.startAudioStream(false, new CompletionListener() { @Override public void onComplete(boolean success) { assertEquals(true, success); manager.pushResource(com.smartdevicelink.test.R.raw.test_audio_square_250hz_80amp_1s, mockFileListener); } }); verify(mockFileListener, timeout(10000)).onComplete(any(Boolean.class)); } public void testSampleAtTargetTimeReturnNull() { BaseAudioDecoder mockDecoder = mock(BaseAudioDecoder.class, Mockito.CALLS_REAL_METHODS); Method sampleAtTargetMethod = getSampleAtTargetMethod(); SampleBuffer sample = SampleBuffer.allocate(1, SampleType.SIGNED_16_BIT, ByteOrder.LITTLE_ENDIAN, 1); Double result; try { result = (Double) sampleAtTargetMethod.invoke(mockDecoder, 1.0, sample, 1, 3, 2); assertNull(result); result = (Double) sampleAtTargetMethod.invoke(mockDecoder, 1.0, sample, 5, 3, 1); assertNull(result); } catch (Exception e) { e.printStackTrace(); fail(); } } public void testSampleAtTargetTimeReturnLastOutputSample() { BaseAudioDecoder mockDecoder = mock(BaseAudioDecoder.class, Mockito.CALLS_REAL_METHODS); Method sampleAtTargetMethod = getSampleAtTargetMethod(); SampleBuffer sample = SampleBuffer.allocate(1, SampleType.SIGNED_16_BIT, ByteOrder.LITTLE_ENDIAN, 1); Double result; Double lastOutputSample = 15.0; try { result = (Double) sampleAtTargetMethod.invoke(mockDecoder, lastOutputSample, sample, 6, 1, 5); assertTrue(result.doubleValue() == lastOutputSample); } catch (Exception e) { e.printStackTrace(); fail(); } } public void testSampleAtTargetTimeReturnOutputSampleGet() { BaseAudioDecoder mockDecoder = mock(BaseAudioDecoder.class, Mockito.CALLS_REAL_METHODS); Method sampleAtTargetMethod = getSampleAtTargetMethod(); SampleBuffer sample = SampleBuffer.allocate(10, SampleType.SIGNED_16_BIT, ByteOrder.LITTLE_ENDIAN, 1); Double result; try { result = (Double) sampleAtTargetMethod.invoke(mockDecoder, 1.0, sample, 1, 1, 2); assertTrue(result == sample.get(1)); } catch (Exception e) { e.printStackTrace(); fail(); } } public void testSampleAtTargetTime() { BaseAudioDecoder mockDecoder = mock(BaseAudioDecoder.class, Mockito.CALLS_REAL_METHODS); Method sampleAtTargetMethod = getSampleAtTargetMethod(); SampleBuffer sample = SampleBuffer.allocate(10, SampleType.SIGNED_16_BIT, ByteOrder.LITTLE_ENDIAN, 1); Double result; try { result = (Double) sampleAtTargetMethod.invoke(mockDecoder, 1.0, sample, 1, 3, 2); assertNotNull(result); } catch (Exception e) { e.printStackTrace(); fail(); } } public void testOutputFormatChanged() { BaseAudioDecoder mockDecoder = mock(BaseAudioDecoder.class, Mockito.CALLS_REAL_METHODS); try { Field outputChannelCountField = BaseAudioDecoder.class.getDeclaredField("outputChannelCount"); Field outputSampleRateField = BaseAudioDecoder.class.getDeclaredField("outputSampleRate"); Field outputSampleTypeField = BaseAudioDecoder.class.getDeclaredField("outputSampleType"); outputChannelCountField.setAccessible(true); outputSampleRateField.setAccessible(true); outputSampleTypeField.setAccessible(true); // channel count, sample rate, sample type int key_channel_count = 0, key_sample_rate = 1, key_sample_type = 2, key_sample_type_result = 3; int[][] tests = new int[][] { { 47, 42000, AudioFormat.ENCODING_PCM_8BIT, SampleType.UNSIGNED_8_BIT }, { 2, 16000, AudioFormat.ENCODING_PCM_16BIT, SampleType.SIGNED_16_BIT }, { 1, 22050, AudioFormat.ENCODING_PCM_FLOAT, SampleType.FLOAT }, { 3, 48000, AudioFormat.ENCODING_INVALID, SampleType.SIGNED_16_BIT }, }; for (int[] test : tests) { int channel_count = test[key_channel_count]; int sample_rate = test[key_sample_rate]; int sample_type = test[key_sample_type]; int sample_type_result = test[key_sample_type_result]; MediaFormat format = new MediaFormat(); format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, channel_count); format.setInteger(MediaFormat.KEY_SAMPLE_RATE, sample_rate); format.setInteger(MediaFormat.KEY_PCM_ENCODING, sample_type); // in case the phone version is old the method does not take sample type into account but // always expected 16 bit. See https://developer.android.com/reference/android/media/MediaFormat.html#KEY_PCM_ENCODING if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) { sample_type_result = SampleType.SIGNED_16_BIT; } mockDecoder.onOutputFormatChanged(format); int output_channel_count = outputChannelCountField.getInt(mockDecoder); int output_sample_rate = outputSampleRateField.getInt(mockDecoder); int output_sample_type = outputSampleTypeField.getInt(mockDecoder); // changing from assertEquals to if and fail so travis gives better results if (channel_count != output_channel_count) { fail("AssertEqualsFailed: channel_count == output_channel_count (" + channel_count + " == " + output_channel_count + ")"); } if (sample_rate != output_sample_rate) { fail("AssertEqualsFailed: sample_rate == output_sample_rate (" + sample_rate + " == " + output_sample_rate + ")"); } if (sample_type_result != output_sample_type) { fail("Assert: sample_type_result == output_sample_type (" + sample_type_result + " == " + output_sample_type + ")"); } } } catch (Exception e) { e.printStackTrace(); fail(); } } public void testPlayAudioFileForManualTest() throws IOException { AudioPassThruCapabilities audioCapabilities = new AudioPassThruCapabilities(SamplingRate._16KHZ, BitsPerSample._16_BIT, AudioType.PCM); final int sampleType = SampleType.SIGNED_16_BIT; final int sampleRate = 16000; final File outputFile = new File(mContext.getCacheDir(), "test_audio_file.wav"); final FileOutputStream fileOutputStream = new FileOutputStream(outputFile); writeWaveHeader(fileOutputStream, sampleRate, sampleType << 3); IAudioStreamListener audioStreamListener = new IAudioStreamListener() { long audioLength = 0; @Override public void sendAudio(byte[] data, int offset, int length, long presentationTimeUs) throws ArrayIndexOutOfBoundsException { ByteBuffer buffer = ByteBuffer.wrap(data, offset, length); this.sendAudio(buffer, presentationTimeUs); } @Override public void sendAudio(ByteBuffer data, long presentationTimeUs) { try { long length = data.limit(); byte[] d = data.array(); fileOutputStream.write(d, 0, (int) length); audioLength += length; RandomAccessFile raf = new RandomAccessFile(outputFile, "rw"); updateWaveHeaderLength(raf, audioLength); } catch (IOException e) { e.printStackTrace(); } } }; final SdlSession mockSession = mock(SdlSession.class); doReturn(audioStreamListener).when(mockSession).startAudioStream(); Answer<Void> audioServiceAnswer = new Answer<Void>() { ISdlServiceListener serviceListener = null; @Override public Void answer(InvocationOnMock invocation) { Method method = invocation.getMethod(); Object[] args = invocation.getArguments(); switch (method.getName()) { case "addServiceListener": // (SessionType serviceType, ISdlServiceListener sdlServiceListener); SessionType sessionType = (SessionType) args[0]; assertEquals(sessionType, SessionType.PCM); serviceListener = (ISdlServiceListener) args[1]; break; case "startAudioService": //(boolean encrypted, AudioStreamingCodec codec, AudioStreamingParams params); Boolean encrypted = (Boolean) args[0]; serviceListener.onServiceStarted(mockSession, SessionType.PCM, encrypted); break; case "stopAudioService": // parameters () serviceListener.onServiceEnded(mockSession, SessionType.PCM); break; } return null; } }; ISdl internalInterface = mock(ISdl.class); doReturn(true).when(internalInterface).isConnected(); doReturn(audioCapabilities).when(internalInterface).getCapability(any(SystemCapabilityType.class)); doAnswer(audioServiceAnswer).when(internalInterface).addServiceListener(any(SessionType.class), any(ISdlServiceListener.class)); doAnswer(audioServiceAnswer).when(internalInterface).startAudioService(any(Boolean.class)); doAnswer(audioServiceAnswer).when(internalInterface).stopAudioService(); final MediaPlayer.OnCompletionListener mockPlayerCompletionListener = mock(MediaPlayer.OnCompletionListener.class); final MediaPlayer player = new MediaPlayer(); player.setOnCompletionListener(mockPlayerCompletionListener); CompletionListener fileCompletionListener = new CompletionListener() { @Override public void onComplete(boolean success) { try { fileOutputStream.flush(); fileOutputStream.close(); player.setDataSource(outputFile.getPath()); player.prepare(); player.start(); } catch (IOException e) { e.printStackTrace(); } } }; final CompletionListener mockFileListener = spy(fileCompletionListener); final AudioStreamManager manager = new AudioStreamManager(internalInterface, mContext); manager.startAudioStream(false, new CompletionListener() { @Override public void onComplete(boolean success) { assertEquals(true, success); manager.pushResource(com.smartdevicelink.test.R.raw.test_audio_square_250hz_80amp_1s, mockFileListener); } }); verify(mockFileListener, timeout(10000)).onComplete(any(Boolean.class)); verify(mockPlayerCompletionListener, timeout(10000)).onCompletion(any(MediaPlayer.class)); } private Method getSampleAtTargetMethod() { Method method = null; try { method = BaseAudioDecoder.class.getDeclaredMethod("sampleAtTargetTime", double.class, SampleBuffer.class, double.class, double.class, double.class); method.setAccessible(true); } catch (NoSuchMethodException e) { e.printStackTrace(); fail(); } return method; } private void setFinalStatic(Field field, Object newValue) throws Exception { field.setAccessible(true); field.set(null, newValue); } private void writeWaveHeader(OutputStream stream, long samplerate, long bitspersample) throws IOException { byte[] header = new byte[44]; // the data header is 36 bytes large long datalength = 36; long audiolength = 0; long format = 1; // 1 = PCM long channels = 1; long blockalign = (channels * bitspersample) >> 3; long byterate = (samplerate * channels * bitspersample) >> 3; // RIFF header. header[0] = 'R'; header[1] = 'I'; header[2] = 'F'; header[3] = 'F'; // Total data length (UInt32). header[4] = (byte)((datalength) & 0xff); header[5] = (byte)((datalength >> 8) & 0xff); header[6] = (byte)((datalength >> 16) & 0xff); header[7] = (byte)((datalength >> 24) & 0xff); // WAVE header. header[8] = 'W'; header[9] = 'A'; header[10] = 'V'; header[11] = 'E'; // Format (fmt) header. header[12] = 'f'; header[13] = 'm'; header[14] = 't'; header[15] = ' '; // Format header size (UInt32). header[16] = 16; header[17] = 0; header[18] = 0; header[19] = 0; // Format type (UInt16). Set 1 for PCM. header[20] = (byte)((format) & 0xff); header[21] = (byte)((format >> 8) & 0xff); // Channels header[22] = (byte)((channels) & 0xff); header[23] = (byte)((channels >> 8) & 0xff); // Sample rate (UInt32). header[24] = (byte)((samplerate) & 0xff); header[25] = (byte)((samplerate >> 8) & 0xff); header[26] = (byte)((samplerate >> 16) & 0xff); header[27] = (byte)((samplerate >> 24) & 0xff); // Byte rate (UInt32). header[28] = (byte)((byterate) & 0xff); header[29] = (byte)((byterate >> 8) & 0xff); header[30] = (byte)((byterate >> 16) & 0xff); header[31] = (byte)((byterate >> 24) & 0xff); // Block alignment (UInt16). header[32] = (byte)((blockalign) & 0xff); header[33] = (byte)((blockalign >> 8) & 0xff); // Bits per sample (UInt16). header[34] = (byte)((bitspersample) & 0xff); header[35] = (byte)((bitspersample >> 8) & 0xff); // Data header header[36] = 'd'; header[37] = 'a'; header[38] = 't'; header[39] = 'a'; // Total audio length (UInt32). header[40] = (byte)((audiolength) & 0xff); header[41] = (byte)((audiolength >> 8) & 0xff); header[42] = (byte)((audiolength >> 16) & 0xff); header[43] = (byte)((audiolength >> 24) & 0xff); stream.write(header, 0, header.length); } /** Updates the data length and audio length of an existing RIFF/WAVE header in the file pointed by the RandomAccessFile object. */ private void updateWaveHeaderLength(RandomAccessFile stream, long audiolength) throws IOException { // the data header is 36 bytes large long datalength = 36 + audiolength; // Seek from the beginning to data length stream.seek(4); // Overwrite total data length stream.write((int)((datalength) & 0xff)); stream.write((int)((datalength >> 8) & 0xff)); stream.write((int)((datalength >> 16) & 0xff)); stream.write((int)((datalength >> 24) & 0xff)); // Seek from the end of data length to audio length stream.seek(40); // overwrite total audio length stream.write((int)((audiolength) & 0xff)); stream.write((int)((audiolength >> 8) & 0xff)); stream.write((int)((audiolength >> 16) & 0xff)); stream.write((int)((audiolength >> 24) & 0xff)); } }
package com.smartdevicelink.test.rpc.datatypes; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import junit.framework.TestCase; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.smartdevicelink.marshal.JsonRPCMarshaller; import com.smartdevicelink.proxy.rpc.DisplayCapabilities; import com.smartdevicelink.proxy.rpc.ImageField; import com.smartdevicelink.proxy.rpc.ImageResolution; import com.smartdevicelink.proxy.rpc.ScreenParams; import com.smartdevicelink.proxy.rpc.TextField; import com.smartdevicelink.proxy.rpc.TouchEventCapabilities; import com.smartdevicelink.proxy.rpc.enums.CharacterSet; import com.smartdevicelink.proxy.rpc.enums.DisplayType; import com.smartdevicelink.proxy.rpc.enums.FileType; import com.smartdevicelink.proxy.rpc.enums.ImageFieldName; import com.smartdevicelink.proxy.rpc.enums.MediaClockFormat; import com.smartdevicelink.proxy.rpc.enums.TextFieldName; import com.smartdevicelink.test.utils.JsonUtils; import com.smartdevicelink.test.utils.Validator; public class DisplayCapabilitiesTests extends TestCase{ private static final boolean GRAPHIC_SUPPORTED = true; private static final int CUSTOM_PRESETS_AVAILABLE = 5; private static final DisplayType DISPLAY_TYPE = DisplayType.NGN; // screen params constants private static final int SCREEN_IMAGE_RESOLUTION_WIDTH = 1250; private static final int SCREEN_IMAGE_RESOLUTION_HEIGHT = 1080; private static final boolean TOUCH_AVAILABLE = true; private static final boolean MULTI_TOUCH_AVAILABLE = false; private static final boolean DOUBLE_PRESS_AVAILABLE = false; private static final int SCREEN_IMAGE_RESOLUTION_HEIGHT_CHANGED = 2160; private static final boolean MULTI_TOUCH_AVAILABLE_CHANGED = true; // textFields constants private static final TextFieldName[] TEXT_FIELD_NAMES = new TextFieldName[] { TextFieldName.alertText1, TextFieldName.alertText2, TextFieldName.mainField1 }; private static final int[] TEXT_FIELD_WIDTHS = new int[] { 25, 25, 30 }; private static final int TEXT_FIELD_ROWS = 1; private static final CharacterSet CHARACTER_SET = CharacterSet.TYPE2SET; private static final TextFieldName TEXT_FIELD_NAME_CHANGED = TextFieldName.statusBar; // imageFields constants private static final ImageFieldName[] IMAGE_FIELD_NAMES = new ImageFieldName[] { ImageFieldName.appIcon, ImageFieldName.graphic, ImageFieldName.softButtonImage }; private static final FileType[] IMAGE_FILE_TYPES = new FileType[] { FileType.GRAPHIC_PNG, FileType.GRAPHIC_JPEG, FileType.GRAPHIC_BMP }; private static final ImageResolution[] IMAGE_RESOLUTIONS = new ImageResolution[3]; private static final Integer IMAGE_RESOLUTION_ITEM_1_WIDTH = 20; private static final Integer IMAGE_RESOLUTION_ITEM_1_HEIGHT = 20; private static final Integer IMAGE_RESOLUTION_ITEM_2_WIDTH = 30; private static final Integer IMAGE_RESOLUTION_ITEM_2_HEIGHT = 30; private static final Integer IMAGE_RESOLUTION_ITEM_3_WIDTH = 40; private static final Integer IMAGE_RESOLUTION_ITEM_3_HEIGHT = 40; private static final ImageFieldName IMAGE_FIELD_NAME_CHANGED = ImageFieldName.showConstantTBTIcon; private static final FileType IMAGE_FILE_TYPE_CHANGED = FileType.AUDIO_MP3; private static final Integer IMAGE_RESOLUTION_HEIGHT_CHANGED= 45; private static final List<String> TEMPLATES_AVAILABLE = Arrays.asList(new String[] { "Media", "Navigation", "Productivity" }); private static final String TEMPLATES_ITEM_CHANGED = "Nothing"; private static final List<MediaClockFormat> MEDIA_CLOCK_FORMATS = Arrays.asList(new MediaClockFormat[] { MediaClockFormat.CLOCK1 }); private static final MediaClockFormat MEDIA_CLOCK_FORMAT_CHANGED = MediaClockFormat.CLOCK3; private DisplayCapabilities msg; private ScreenParams screenParams; private List<TextField> textFields; private List<ImageField> imageFields; private ImageResolution imageResolution; private TouchEventCapabilities touchEventCapabilities; @Override public void setUp(){ msg = new DisplayCapabilities(); createCustomObjects(); msg.setGraphicSupported(GRAPHIC_SUPPORTED); msg.setNumCustomPresetsAvailable(CUSTOM_PRESETS_AVAILABLE); msg.setDisplayType(DISPLAY_TYPE); msg.setImageFields(imageFields); msg.setTextFields(textFields); msg.setMediaClockFormats(MEDIA_CLOCK_FORMATS); msg.setScreenParams(screenParams); msg.setTemplatesAvailable(TEMPLATES_AVAILABLE); } private void createCustomObjects(){ ImageResolution imageResolutionForImageFields1 = new ImageResolution(); imageResolutionForImageFields1.setResolutionWidth(IMAGE_RESOLUTION_ITEM_1_WIDTH); imageResolutionForImageFields1.setResolutionHeight(IMAGE_RESOLUTION_ITEM_1_HEIGHT); IMAGE_RESOLUTIONS[0] = imageResolutionForImageFields1; ImageResolution imageResolutionForImageFields2 = new ImageResolution(); imageResolutionForImageFields2.setResolutionWidth(IMAGE_RESOLUTION_ITEM_2_WIDTH); imageResolutionForImageFields2.setResolutionHeight(IMAGE_RESOLUTION_ITEM_2_HEIGHT); IMAGE_RESOLUTIONS[1] = imageResolutionForImageFields2; ImageResolution imageResolutionForImageFields3 = new ImageResolution(); imageResolutionForImageFields3.setResolutionWidth(IMAGE_RESOLUTION_ITEM_3_WIDTH); imageResolutionForImageFields3.setResolutionHeight(IMAGE_RESOLUTION_ITEM_3_HEIGHT); IMAGE_RESOLUTIONS[2] = imageResolutionForImageFields3; imageResolution = new ImageResolution(); imageResolution.setResolutionWidth(SCREEN_IMAGE_RESOLUTION_WIDTH); imageResolution.setResolutionHeight(SCREEN_IMAGE_RESOLUTION_HEIGHT); touchEventCapabilities = new TouchEventCapabilities(); touchEventCapabilities.setPressAvailable(TOUCH_AVAILABLE); touchEventCapabilities.setMultiTouchAvailable(MULTI_TOUCH_AVAILABLE); touchEventCapabilities.setDoublePressAvailable(DOUBLE_PRESS_AVAILABLE); screenParams = new ScreenParams(); screenParams.setImageResolution(imageResolution); screenParams.setTouchEventAvailable(touchEventCapabilities); textFields = new ArrayList<TextField>(TEXT_FIELD_NAMES.length); for(int i = 0; i < TEXT_FIELD_NAMES.length; i++){ TextField textField = new TextField(); textField.setName(TEXT_FIELD_NAMES[i]); textField.setCharacterSet(CHARACTER_SET); textField.setWidth(TEXT_FIELD_WIDTHS[i]); textField.setRows(TEXT_FIELD_ROWS); textFields.add(textField); } imageFields = new ArrayList<ImageField>(IMAGE_FIELD_NAMES.length); for(int i = 0; i < IMAGE_FIELD_NAMES.length; i++){ ImageField imageField = new ImageField(); imageField.setName(IMAGE_FIELD_NAMES[i]); List<FileType> fileList = new ArrayList<FileType>(); for(int j = 0; j < IMAGE_FILE_TYPES.length; j++){ fileList.add(IMAGE_FILE_TYPES[j]); } imageField.setImageTypeSupported(fileList); imageField.setImageResolution(IMAGE_RESOLUTIONS[i]); imageFields.add(imageField); } } public void testGraphicSupported(){ boolean copy = msg.getGraphicSupported(); assertEquals("Input value didn't match expected value.", GRAPHIC_SUPPORTED, copy); } public void testNumPresetsAvailable(){ int copy = msg.getNumCustomPresetsAvailable(); assertEquals("Input value didn't match expected value.", CUSTOM_PRESETS_AVAILABLE, copy); } public void testDisplayType(){ DisplayType copy = msg.getDisplayType(); assertEquals("Input value didn't match expected value.", DISPLAY_TYPE, copy); } public void testScreenParams(){ ScreenParams copy = msg.getScreenParams(); assertTrue("Input value didn't match expected value.", Validator.validateScreenParams(screenParams, copy)); } public void testGetScreenParams(){ ScreenParams copy1 = msg.getScreenParams(); ImageResolution imageResolution1 = copy1.getImageResolution(); imageResolution1.setResolutionHeight(SCREEN_IMAGE_RESOLUTION_HEIGHT_CHANGED); TouchEventCapabilities touchEvent1 = copy1.getTouchEventAvailable(); touchEvent1.setMultiTouchAvailable(MULTI_TOUCH_AVAILABLE_CHANGED); ScreenParams copy2 = msg.getScreenParams(); assertNotSame("Screen parameters were not defensive copied", copy1, copy2); assertFalse("Copies have the same values", Validator.validateScreenParams(copy1, copy2)); } public void testSetScreenParams(){ ScreenParams copy1 = msg.getScreenParams(); ImageResolution imageResolution1 = copy1.getImageResolution(); TouchEventCapabilities touchEvent1 = copy1.getTouchEventAvailable(); msg.setScreenParams(copy1); imageResolution1.setResolutionHeight(SCREEN_IMAGE_RESOLUTION_HEIGHT_CHANGED); touchEvent1.setMultiTouchAvailable(MULTI_TOUCH_AVAILABLE_CHANGED); ScreenParams copy2 = msg.getScreenParams(); assertNotSame("Screen parameters were not defensive copied", copy1, copy2); assertFalse("Copies have the same values", Validator.validateScreenParams(copy1, copy2)); } public void testTemplatesAvailable(){ List<String> copy = msg.getTemplatesAvailable(); assertEquals("Templates available size didn't match expected size.", TEMPLATES_AVAILABLE.size(), copy.size()); for(int i = 0; i < TEMPLATES_AVAILABLE.size(); i++){ assertEquals("Template data at index " + i + " didn't match expected data.", TEMPLATES_AVAILABLE.get(i), copy.get(i)); } } public void testGetTemplatesAvailable() { List<String> copy1 = msg.getTemplatesAvailable(); copy1.set(0, TEMPLATES_ITEM_CHANGED); List<String> copy2 = msg.getTemplatesAvailable(); assertNotSame("Templates list was not defensive copied", copy1, copy2); assertFalse("Copies have the same values", Validator.validateStringList(copy1, copy2)); } public void testSetTemplatesAvailable() { List<String> copy1 = msg.getTemplatesAvailable(); msg.setTemplatesAvailable(copy1); copy1.set(0, TEMPLATES_ITEM_CHANGED); List<String> copy2 = msg.getTemplatesAvailable(); assertNotSame("Templates list was not defensive copied", copy1, copy2); assertFalse("Copies have the same values", Validator.validateStringList(copy1, copy2)); } public void testMediaClockFormats(){ List<MediaClockFormat> copy = msg.getMediaClockFormats(); assertEquals("Media clock formats size didn't match expected size.", MEDIA_CLOCK_FORMATS.size(), copy.size()); for(int i = 0; i < MEDIA_CLOCK_FORMATS.size(); i++){ assertEquals("Media clock format data at index " + i + " didn't match expected data.", MEDIA_CLOCK_FORMATS.get(i), copy.get(i)); } } public void testGetMediaClockFormats() { List<MediaClockFormat> copy1 = msg.getMediaClockFormats(); copy1.set(0, MEDIA_CLOCK_FORMAT_CHANGED); List<MediaClockFormat> copy2 = msg.getMediaClockFormats(); assertNotSame("Templates list was not defensive copied", copy1, copy2); assertEquals("Media clock formats list lengths do not match", copy1.size(), copy2.size()); for (int index = 0; index < copy1.size(); index++) { assertEquals("Input value didn't match expected value", copy1.get(index), copy2.get(index)); } } public void testSetMediaClockFormats() { List<MediaClockFormat> copy1 = msg.getMediaClockFormats(); msg.setMediaClockFormats(copy1); copy1.set(0, MEDIA_CLOCK_FORMAT_CHANGED); List<MediaClockFormat> copy2 = msg.getMediaClockFormats(); assertNotSame("Templates list was not defensive copied", copy1, copy2); assertEquals("Media clock formats list lengths do not match", copy1.size(), copy2.size()); for (int index = 0; index < copy1.size(); index++) { assertEquals("Input value didn't match expected value", copy1.get(index), copy2.get(index)); } } public void testTextFields(){ List<TextField> copy = msg.getTextFields(); assertEquals("Text fields size didn't match expected size.", textFields.size(), copy.size()); for(int i = 0; i < textFields.size(); i++){ assertTrue("Text field data at index " + i + " didn't match expected data.", Validator.validateTextFields(textFields.get(i), copy.get(i))); } } public void testGetTextFields() { List<TextField> copy1 = msg.getTextFields(); TextField firstItem = copy1.get(0); firstItem.setName(TEXT_FIELD_NAME_CHANGED); List<TextField> copy2 = msg.getTextFields(); assertNotSame("Text field list was not defensive copied", copy1, copy2); //test the first object for different values, and test the rest of the objects in the list for same values TextField textFieldFirst1 = copy1.get(0); TextField textFieldFirst2 = copy2.get(0); assertNotSame("Text field was not defensive copied", textFieldFirst1, textFieldFirst2); assertFalse("Text field objects matched", Validator.validateTextFields(textFieldFirst1, textFieldFirst2)); for (int index = 1; index < copy1.size(); index++) { TextField textFieldCopy1 = copy1.get(index); TextField textFieldCopy2 = copy2.get(index); assertTrue("Input value didn't match expected value", Validator.validateTextFields(textFieldCopy1, textFieldCopy2)); } } public void testSetTextFields() { List<TextField> copy1 = msg.getTextFields(); TextField firstItem = copy1.get(0); msg.setTextFields(copy1); firstItem.setName(TEXT_FIELD_NAME_CHANGED); List<TextField> copy2 = msg.getTextFields(); assertNotSame("Text field list was not defensive copied", copy1, copy2); //test the first object for different values, and test the rest of the objects in the list for same values TextField textFieldFirst1 = copy1.get(0); TextField textFieldFirst2 = copy2.get(0); assertNotSame("Text field was not defensive copied", textFieldFirst1, textFieldFirst2); assertFalse("Text field objects matched", Validator.validateTextFields(textFieldFirst1, textFieldFirst2)); for (int index = 1; index < copy1.size(); index++) { TextField textFieldCopy1 = copy1.get(index); TextField textFieldCopy2 = copy2.get(index); assertTrue("Input value didn't match expected value", Validator.validateTextFields(textFieldCopy1, textFieldCopy2)); } } public void testImageFields(){ List<ImageField> copy = msg.getImageFields(); assertEquals("Text fields size didn't match expected size.", imageFields.size(), copy.size()); for(int i = 0; i < imageFields.size(); i++){ try { System.out.println(imageFields.get(i).serializeJSON()); } catch (JSONException e) { e.printStackTrace(); } assertTrue("Text field data at index " + i + " didn't match expected data.", Validator.validateImageFields(imageFields.get(i), copy.get(i))); } } public void testGetImageFields() { List<ImageField> copy1 = msg.getImageFields(); ImageField firstImageField = copy1.get(0); List<FileType> firstFileTypeInFirstImageField = firstImageField.getImageTypeSupported(); ImageResolution firstImageResolution = firstImageField.getImageResolution(); firstImageField.setName(IMAGE_FIELD_NAME_CHANGED); firstFileTypeInFirstImageField.set(0, IMAGE_FILE_TYPE_CHANGED); firstImageResolution.setResolutionHeight(IMAGE_RESOLUTION_HEIGHT_CHANGED); List<ImageField> copy2 = msg.getImageFields(); assertNotSame("Image field list was not defensive copied", copy1, copy2); //test the first object for different values, and test the rest of the objects in the list for same values ImageField imageFieldFirst1 = copy1.get(0); ImageField imageFieldFirst2 = copy2.get(0); assertNotSame("Image field was not defensive copied", imageFieldFirst1, imageFieldFirst2); List<FileType> firstFileTypeImageField1 = imageFieldFirst1.getImageTypeSupported(); List<FileType> firstFileTypeImageField2 = imageFieldFirst2.getImageTypeSupported(); ImageResolution firstImageResolution1 = imageFieldFirst1.getImageResolution(); ImageResolution firstImageResolution2 = imageFieldFirst2.getImageResolution(); assertNotSame("First file type list was not defensive copied", firstFileTypeImageField1, firstFileTypeImageField2); assertNotSame("First image resolution was not defensive copied", firstImageResolution1, firstImageResolution2); assertFalse("Image field objects matched", Validator.validateImageFields(imageFieldFirst1, imageFieldFirst2)); for (int index = 1; index < copy1.size(); index++) { ImageField imageFieldCopy1 = copy1.get(index); ImageField imageFieldCopy2 = copy2.get(index); assertNotSame("Image field was not defensive copied", imageFieldFirst1, imageFieldFirst2); assertNotSame("First file type list was not defensive copied", firstFileTypeImageField1, firstFileTypeImageField2); assertNotSame("First image resolution was not defensive copied", firstImageResolution1, firstImageResolution2); assertTrue("Input value didn't match expected value", Validator.validateImageFields(imageFieldCopy1, imageFieldCopy2)); } } public void testSetImageFields() { List<ImageField> copy1 = msg.getImageFields(); ImageField firstImageField = copy1.get(0); List<FileType> firstFileTypeInFirstImageField = firstImageField.getImageTypeSupported(); ImageResolution firstImageResolution = firstImageField.getImageResolution(); msg.setImageFields(copy1); firstImageField.setName(IMAGE_FIELD_NAME_CHANGED); firstFileTypeInFirstImageField.set(0, IMAGE_FILE_TYPE_CHANGED); firstImageResolution.setResolutionHeight(IMAGE_RESOLUTION_HEIGHT_CHANGED); List<ImageField> copy2 = msg.getImageFields(); assertNotSame("Image field list was not defensive copied", copy1, copy2); //test the first object for different values, and test the rest of the objects in the list for same values ImageField imageFieldFirst1 = copy1.get(0); ImageField imageFieldFirst2 = copy2.get(0); assertNotSame("Image field was not defensive copied", imageFieldFirst1, imageFieldFirst2); List<FileType> firstFileTypeImageField1 = imageFieldFirst1.getImageTypeSupported(); List<FileType> firstFileTypeImageField2 = imageFieldFirst2.getImageTypeSupported(); ImageResolution firstImageResolution1 = imageFieldFirst1.getImageResolution(); ImageResolution firstImageResolution2 = imageFieldFirst2.getImageResolution(); assertNotSame("First file type list was not defensive copied", firstFileTypeImageField1, firstFileTypeImageField2); assertNotSame("First image resolution was not defensive copied", firstImageResolution1, firstImageResolution2); assertFalse("Image field objects matched", Validator.validateImageFields(imageFieldFirst1, imageFieldFirst2)); for (int index = 1; index < copy1.size(); index++) { ImageField imageFieldCopy1 = copy1.get(index); ImageField imageFieldCopy2 = copy2.get(index); assertNotSame("Image field was not defensive copied", imageFieldFirst1, imageFieldFirst2); assertNotSame("First file type list was not defensive copied", firstFileTypeImageField1, firstFileTypeImageField2); assertNotSame("First image resolution was not defensive copied", firstImageResolution1, firstImageResolution2); assertTrue("Input value didn't match expected value", Validator.validateImageFields(imageFieldCopy1, imageFieldCopy2)); } } public void testJson(){ JSONObject reference = new JSONObject(); JSONObject screenParams = new JSONObject(), imageResolution = new JSONObject(), touchEventCapabilities = new JSONObject(); JSONArray mediaClockFormats = new JSONArray(), textFields = new JSONArray(), imageFields = new JSONArray(); try{ reference.put(DisplayCapabilities.KEY_NUM_CUSTOM_PRESETS_AVAILABLE, CUSTOM_PRESETS_AVAILABLE); reference.put(DisplayCapabilities.KEY_GRAPHIC_SUPPORTED, GRAPHIC_SUPPORTED); reference.put(DisplayCapabilities.KEY_DISPLAY_TYPE, DISPLAY_TYPE); reference.put(DisplayCapabilities.KEY_TEMPLATES_AVAILABLE, JsonUtils.createJsonArray(TEMPLATES_AVAILABLE)); for(MediaClockFormat format : MEDIA_CLOCK_FORMATS){ mediaClockFormats.put(format); } reference.put(DisplayCapabilities.KEY_MEDIA_CLOCK_FORMATS, mediaClockFormats); // text fields for(TextField textField : this.textFields){ JSONObject textFieldJson = new JSONObject(); textFieldJson.put(TextField.KEY_CHARACTER_SET, textField.getCharacterSet()); textFieldJson.put(TextField.KEY_NAME, textField.getName()); textFieldJson.put(TextField.KEY_ROWS, textField.getRows()); textFieldJson.put(TextField.KEY_WIDTH, textField.getWidth()); textFields.put(textFieldJson); } reference.put(DisplayCapabilities.KEY_TEXT_FIELDS, textFields); // image fields for(ImageField imageField : this.imageFields){ JSONObject imageFieldJson = new JSONObject(); imageFieldJson.put(ImageField.KEY_IMAGE_TYPE_SUPPORTED, imageField.getImageTypeSupported()); imageFieldJson.put(ImageField.KEY_NAME, imageField.getName()); ImageResolution resolution = imageField.getImageResolution(); JSONObject resolutionJson = new JSONObject(); resolutionJson.put(ImageResolution.KEY_RESOLUTION_HEIGHT, resolution.getResolutionHeight()); resolutionJson.put(ImageResolution.KEY_RESOLUTION_WIDTH, resolution.getResolutionWidth()); imageFieldJson.put(ImageField.KEY_IMAGE_RESOLUTION, resolutionJson); imageFields.put(imageFieldJson); } reference.put(DisplayCapabilities.KEY_IMAGE_FIELDS, imageFields); // screen params ImageResolution resolution = this.screenParams.getImageResolution(); imageResolution.put(ImageResolution.KEY_RESOLUTION_HEIGHT, resolution.getResolutionHeight()); imageResolution.put(ImageResolution.KEY_RESOLUTION_WIDTH, resolution.getResolutionWidth()); screenParams.put(ScreenParams.KEY_RESOLUTION, imageResolution); TouchEventCapabilities touchCapabilities = this.touchEventCapabilities; touchEventCapabilities.put(TouchEventCapabilities.KEY_PRESS_AVAILABLE, touchCapabilities.getPressAvailable()); touchEventCapabilities.put(TouchEventCapabilities.KEY_DOUBLE_PRESS_AVAILABLE, touchCapabilities.getDoublePressAvailable()); touchEventCapabilities.put(TouchEventCapabilities.KEY_MULTI_TOUCH_AVAILABLE, touchCapabilities.getMultiTouchAvailable()); screenParams.put(ScreenParams.KEY_TOUCH_EVENT_AVAILABLE, touchEventCapabilities); reference.put(DisplayCapabilities.KEY_SCREEN_PARAMS, screenParams); JSONObject underTest = msg.serializeJSON(); assertEquals("JSON size didn't match expected size.", reference.length(), underTest.length()); Iterator<?> iterator = reference.keys(); while(iterator.hasNext()){ String key = (String) iterator.next(); if(key.equals(DisplayCapabilities.KEY_IMAGE_FIELDS)){ JSONArray referenceArray = JsonUtils.readJsonArrayFromJsonObject(reference, key); JSONArray underTestArray = JsonUtils.readJsonArrayFromJsonObject(underTest, key); assertEquals("Image field size didn't match expected size.", referenceArray.length(), underTestArray.length()); for(int i = 0; i < referenceArray.length(); i++){ Hashtable<String, Object> hashReference = JsonRPCMarshaller.deserializeJSONObject(referenceArray.getJSONObject(i)); Hashtable<String, Object> hashTest= JsonRPCMarshaller.deserializeJSONObject(underTestArray.getJSONObject(i)); assertTrue("Image field at index " + i + " didn't match expected value.", Validator.validateImageFields(new ImageField(hashReference), new ImageField(hashTest))); } } else if(key.equals(DisplayCapabilities.KEY_TEXT_FIELDS)){ JSONArray referenceArray = JsonUtils.readJsonArrayFromJsonObject(reference, key); JSONArray underTestArray = JsonUtils.readJsonArrayFromJsonObject(underTest, key); assertEquals("Text field size didn't match expected size.", referenceArray.length(), underTestArray.length()); for(int i = 0; i < referenceArray.length(); i++){ Hashtable<String, Object> hashReference = JsonRPCMarshaller.deserializeJSONObject(referenceArray.getJSONObject(i)); Hashtable<String, Object> hashTest= JsonRPCMarshaller.deserializeJSONObject(underTestArray.getJSONObject(i)); assertTrue("Text field at index " + i + " didn't match expected value.", Validator.validateTextFields(new TextField(hashReference), new TextField(hashTest))); } } else if(key.equals(DisplayCapabilities.KEY_TEMPLATES_AVAILABLE)){ JSONArray referenceArray = JsonUtils.readJsonArrayFromJsonObject(reference, key); JSONArray underTestArray = JsonUtils.readJsonArrayFromJsonObject(underTest, key); assertEquals("Template list size didn't match expected size.", referenceArray.length(), underTestArray.length()); for(int i = 0; i < referenceArray.length(); i++){ assertTrue("Template field at index " + i + " didn't match expected value.", Validator.validateText(referenceArray.getString(i), underTestArray.getString(i))); } } else if(key.equals(DisplayCapabilities.KEY_SCREEN_PARAMS)){ JSONObject referenceArray = JsonUtils.readJsonObjectFromJsonObject(reference, key); JSONObject underTestArray = JsonUtils.readJsonObjectFromJsonObject(underTest, key); Hashtable<String, Object> hashReference = JsonRPCMarshaller.deserializeJSONObject(referenceArray); Hashtable<String, Object> hashTest= JsonRPCMarshaller.deserializeJSONObject(underTestArray); assertTrue("Screen params value didn't match expected value.", Validator.validateScreenParams( new ScreenParams(hashReference), new ScreenParams(hashTest))); } else if(key.equals(DisplayCapabilities.KEY_MEDIA_CLOCK_FORMATS)){ JSONArray referenceArray = JsonUtils.readJsonArrayFromJsonObject(reference, key); JSONArray underTestArray = JsonUtils.readJsonArrayFromJsonObject(underTest, key); assertEquals("Media clock format list size didn't match expected size.", referenceArray.length(), underTestArray.length()); for(int i = 0; i < referenceArray.length(); i++){ assertTrue("Media clock format at index " + i + " didn't match expected value.", Validator.validateText(referenceArray.getString(i), underTestArray.getString(i))); } } else{ assertEquals("JSON value didn't match expected value for key \"" + key + "\".", JsonUtils.readObjectFromJsonObject(reference, key), JsonUtils.readObjectFromJsonObject(underTest, key)); } } }catch(JSONException e){ /* do nothing */ } } public void testNull(){ DisplayCapabilities msg = new DisplayCapabilities(); assertNotNull("Null object creation failed.", msg); assertNull("Display type wasn't set, but getter method returned an object.", msg.getDisplayType()); assertNull("Graphic supported wasn't set, but getter method returned an object.", msg.getGraphicSupported()); assertNull("Image field list wasn't set, but getter method returned an object.", msg.getImageFields()); assertNull("Media clock format list wasn't set, but getter method returned an object.", msg.getMediaClockFormats()); assertNull("Num of custom presets wasn't set, but getter method returned an object.", msg.getNumCustomPresetsAvailable()); assertNull("Screen params wasn't set, but getter method returned an object.", msg.getScreenParams()); assertNull("Templates available list wasn't set, but getter method returned an object.", msg.getTemplatesAvailable()); assertNull("Text fields list wasn't set, but getter method returned an object.", msg.getTextFields()); } }
package org.jboss.as.server.deployment.module; import java.io.Closeable; import java.io.IOException; import java.util.ArrayDeque; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.jboss.as.server.ServerLogger; import org.jboss.as.server.deployment.Attachable; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.DeploymentUtils; import org.jboss.as.server.deployment.SubDeploymentMarker; import org.jboss.as.server.deployment.annotation.ResourceRootIndexer; import org.jboss.as.server.moduleservice.ExternalModuleService; import org.jboss.as.server.moduleservice.ServiceModuleLoader; import org.jboss.modules.ModuleIdentifier; import org.jboss.vfs.VFS; import org.jboss.vfs.VFSUtils; import org.jboss.vfs.VirtualFile; /** * A processor which adds class path entries for each manifest entry. * <p/> * <p/> * <p/> * </li> * <li> * If the Class-Path entry is external to the deployment then it is handled by the external jar service.</li> * <li> * If the entry refers to a sibling deployment then a dependency is added on that deployment. If this deployment is * not present then this deployment will block until it is.</li> * <li> * If the Class-Path entry points to a jar inside the ear that is not a deployment and not a /lib jar then a reference is added * to this jars {@link AdditionalModuleSpecification}</li> * </ul> * * @author Stuart Douglas * @author Ales Justin */ public final class ManifestClassPathProcessor implements DeploymentUnitProcessor { private static final String[] EMPTY_STRING_ARRAY = {}; /** * We only allow a single deployment at a time to be run through the class path processor. * <p/> * This is because if multiple sibling deployments reference the same item we need to make sure that they end up * with the same external module, and do not both create an external module with the same name. */ public synchronized void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final DeploymentUnit parent = deploymentUnit.getParent(); final DeploymentUnit topLevelDeployment = parent == null ? deploymentUnit : parent; final VirtualFile topLevelRoot = topLevelDeployment.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot(); final ExternalModuleService externalModuleService = topLevelDeployment.getAttachment(Attachments.EXTERNAL_MODULE_SERVICE); final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT); //These are resource roots that are already accessible by default //such as ear/lib jars an web-inf/lib jars final Set<VirtualFile> existingAccessibleRoots = new HashSet<VirtualFile>(); final Map<VirtualFile, ResourceRoot> subDeployments = new HashMap<VirtualFile, ResourceRoot>(); for (ResourceRoot root : DeploymentUtils.allResourceRoots(topLevelDeployment)) { if (SubDeploymentMarker.isSubDeployment(root)) { subDeployments.put(root.getRoot(), root); } else if (ModuleRootMarker.isModuleRoot(root)) { //top level module roots are already accessible, as they are either //ear/lib jars, or jars that are already part of the deployment existingAccessibleRoots.add(root.getRoot()); } } final ArrayDeque<RootEntry> resourceRoots = new ArrayDeque<RootEntry>(); if (deploymentUnit.getParent() != null) { //top level deployments already had their exiting roots processed above for (ResourceRoot root : DeploymentUtils.allResourceRoots(deploymentUnit)) { if (ModuleRootMarker.isModuleRoot(root)) { //if this is a sub deployment of an ear we need to make sure we don't //re-add existing module roots as class path entries //this will mainly be WEB-INF/(lib|classes) entries existingAccessibleRoots.add(root.getRoot()); } } } for (ResourceRoot root : DeploymentUtils.allResourceRoots(deploymentUnit)) { //add this to the list of roots to be processed resourceRoots.add(new RootEntry(deploymentUnit, root)); } // build a map of the additional module locations // note that if a resource root has been added to two different additional modules // and is then referenced via a Class-Path entry the behaviour is undefined final Map<VirtualFile, AdditionalModuleSpecification> additionalModules = new HashMap<VirtualFile, AdditionalModuleSpecification>(); for (AdditionalModuleSpecification module : topLevelDeployment.getAttachmentList(Attachments.ADDITIONAL_MODULES)) { for (ResourceRoot additionalModuleResourceRoot : module.getResourceRoots()) { additionalModules.put(additionalModuleResourceRoot.getRoot(), module); } } //additional resource roots may be added as while (!resourceRoots.isEmpty()) { final RootEntry entry = resourceRoots.pop(); final ResourceRoot resourceRoot = entry.resourceRoot; final Attachable target = entry.target; //if this is a top level deployment we do not want to process sub deployments if (SubDeploymentMarker.isSubDeployment(resourceRoot) && resourceRoot != deploymentRoot) { continue; } final String[] items = getClassPathEntries(resourceRoot); for (final String item : items) { if (item.isEmpty() || item.equals(".")) { //a class path of . causes problems and is unnecessary, see WFLY-2725 continue; } //first try and resolve relative to the manifest resource root final VirtualFile classPathFile = resourceRoot.getRoot().getParent().getChild(item); //then resolve relative to the deployment root final VirtualFile topLevelClassPathFile = deploymentRoot.getRoot().getParent().getChild(item); if (item.startsWith("/")) { if (externalModuleService.isValid(item)) { final ModuleIdentifier moduleIdentifier = externalModuleService.addExternalModule(item); target.addToAttachmentList(Attachments.CLASS_PATH_ENTRIES, moduleIdentifier); ServerLogger.DEPLOYMENT_LOGGER.debugf("Resource %s added as external jar %s", classPathFile, resourceRoot.getRoot()); } else { ServerLogger.DEPLOYMENT_LOGGER.classPathEntryNotValid(item, resourceRoot.getRoot().getPathName()); } } else { if (classPathFile.exists()) { //we need to check that this class path item actually lies within the deployment boolean found = false; VirtualFile file = classPathFile.getParent(); while (file != null) { if (file.equals(topLevelRoot)) { found = true; } file = file.getParent(); } if (!found) { ServerLogger.DEPLOYMENT_LOGGER.classPathEntryNotValid(item, resourceRoot.getRoot().getPathName()); } else { handlingExistingClassPathEntry(resourceRoots, topLevelDeployment, topLevelRoot, subDeployments, additionalModules, existingAccessibleRoots, resourceRoot, target, classPathFile); } } else if (topLevelClassPathFile.exists()) { boolean found = false; VirtualFile file = topLevelClassPathFile.getParent(); while (file != null) { if (file.equals(topLevelRoot)) { found = true; } file = file.getParent(); } if (!found) { ServerLogger.DEPLOYMENT_LOGGER.classPathEntryNotValid(item, resourceRoot.getRoot().getPathName()); } else { handlingExistingClassPathEntry(resourceRoots, topLevelDeployment, topLevelRoot, subDeployments, additionalModules, existingAccessibleRoots, resourceRoot, target, topLevelClassPathFile); } } else { ServerLogger.DEPLOYMENT_LOGGER.classPathEntryNotValid(item, resourceRoot.getRoot().getPathName()); } } } } } private void handlingExistingClassPathEntry(final ArrayDeque<RootEntry> resourceRoots, final DeploymentUnit topLevelDeployment, final VirtualFile topLevelRoot, final Map<VirtualFile, ResourceRoot> subDeployments, final Map<VirtualFile, AdditionalModuleSpecification> additionalModules, final Set<VirtualFile> existingAccessibleRoots, final ResourceRoot resourceRoot, final Attachable target, final VirtualFile classPathFile) throws DeploymentUnitProcessingException { if (existingAccessibleRoots.contains(classPathFile)) { ServerLogger.DEPLOYMENT_LOGGER.debugf("Class-Path entry %s in %s ignored, as target is already accessible", classPathFile, resourceRoot.getRoot()); } else if (additionalModules.containsKey(classPathFile)) { final AdditionalModuleSpecification moduleSpecification = additionalModules.get(classPathFile); //as class path entries are exported, transitive dependencies will also be available target.addToAttachmentList(Attachments.CLASS_PATH_ENTRIES, moduleSpecification.getModuleIdentifier()); } else if (subDeployments.containsKey(classPathFile)) { //now we need to calculate the sub deployment module identifier //unfortunately the sub deployment has not been setup yet, so we cannot just //get it from the sub deployment directly final ResourceRoot otherRoot = subDeployments.get(classPathFile); target.addToAttachmentList(Attachments.CLASS_PATH_ENTRIES, ModuleIdentifierProcessor.createModuleIdentifier(otherRoot.getRootName(), otherRoot, topLevelDeployment, topLevelRoot, false)); } else { ModuleIdentifier identifier = createAdditionalModule(resourceRoot, topLevelDeployment, topLevelRoot, additionalModules, classPathFile, resourceRoots); target.addToAttachmentList(Attachments.CLASS_PATH_ENTRIES, identifier); } } private ModuleIdentifier createAdditionalModule(final ResourceRoot resourceRoot, final DeploymentUnit topLevelDeployment, final VirtualFile topLevelRoot, final Map<VirtualFile, AdditionalModuleSpecification> additionalModules, final VirtualFile classPathFile, final ArrayDeque<RootEntry> resourceRoots) throws DeploymentUnitProcessingException { final ResourceRoot root = createResourceRoot(classPathFile); final String pathName = root.getRoot().getPathNameRelativeTo(topLevelRoot); ModuleIdentifier identifier = ModuleIdentifier.create(ServiceModuleLoader.MODULE_PREFIX + topLevelDeployment.getName() + "." + pathName); AdditionalModuleSpecification module = new AdditionalModuleSpecification(identifier, root); topLevelDeployment.addToAttachmentList(Attachments.ADDITIONAL_MODULES, module); additionalModules.put(classPathFile, module); resourceRoot.addToAttachmentList(Attachments.CLASS_PATH_RESOURCE_ROOTS, root); //add this to the list of roots to be processed, so transitive class path entries will be respected resourceRoots.add(new RootEntry(module, root)); return identifier; } private static String[] getClassPathEntries(final ResourceRoot resourceRoot) { final Manifest manifest; try { manifest = VFSUtils.getManifest(resourceRoot.getRoot()); } catch (IOException e) { throw new RuntimeException(e); } if (manifest == null) { // no class path to process! return EMPTY_STRING_ARRAY; } final String classPathString = manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH); if (classPathString == null) { // no entry return EMPTY_STRING_ARRAY; } return classPathString.split("\\s+"); } /** * Creates a {@link ResourceRoot} for the passed {@link VirtualFile file} and adds it to the list of {@link ResourceRoot}s * in the {@link DeploymentUnit deploymentUnit} * * * @param file The file for which the resource root will be created * @return Returns the created {@link ResourceRoot} * @throws java.io.IOException */ private synchronized ResourceRoot createResourceRoot(final VirtualFile file) throws DeploymentUnitProcessingException { try { final Closeable closable = file.isFile() ? VFS.mountZip(file, file, TempFileProviderService.provider()) : null; final MountHandle mountHandle = new MountHandle(closable); final ResourceRoot resourceRoot = new ResourceRoot(file, mountHandle); ModuleRootMarker.mark(resourceRoot); ResourceRootIndexer.indexResourceRoot(resourceRoot); return resourceRoot; } catch (IOException e) { throw new RuntimeException(e); } } /** * {@inheritDoc} */ public void undeploy(final DeploymentUnit context) { } private class RootEntry { private final ResourceRoot resourceRoot; private final Attachable target; private RootEntry(final Attachable target, final ResourceRoot resourceRoot) { this.target = target; this.resourceRoot = resourceRoot; } } }
package org.zanata.webtrans.client.presenter; import static org.easymock.EasyMock.and; import static org.easymock.EasyMock.capture; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.eq; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.isA; import static org.easymock.EasyMock.notNull; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.reset; import static org.easymock.EasyMock.verify; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import net.customware.gwt.presenter.client.EventBus; import org.easymock.Capture; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.zanata.common.TransUnitCount; import org.zanata.common.TransUnitWords; import org.zanata.common.TranslationStats; import org.zanata.webtrans.client.events.DocumentSelectionEvent; import org.zanata.webtrans.client.events.DocumentStatsUpdatedEvent; import org.zanata.webtrans.client.events.DocumentStatsUpdatedEventHandler; import org.zanata.webtrans.client.events.NotificationEvent; import org.zanata.webtrans.client.events.NotificationEvent.Severity; import org.zanata.webtrans.client.events.NotificationEventHandler; import org.zanata.webtrans.client.events.ProjectStatsUpdatedEvent; import org.zanata.webtrans.client.events.ProjectStatsUpdatedEventHandler; import org.zanata.webtrans.client.history.History; import org.zanata.webtrans.client.history.HistoryToken; import org.zanata.webtrans.client.history.Window; import org.zanata.webtrans.client.presenter.AppPresenter.Display; import org.zanata.webtrans.client.resources.WebTransMessages; import org.zanata.webtrans.shared.auth.Identity; import org.zanata.webtrans.shared.model.DocumentId; import org.zanata.webtrans.shared.model.DocumentInfo; import org.zanata.webtrans.shared.model.Person; import org.zanata.webtrans.shared.model.WorkspaceContext; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; @Test(groups = { "unit-tests" }) public class AppPresenterTest { private static final String TEST_PERSON_NAME = "Mister Ed"; private static final String TEST_WORKSPACE_NAME = "Test Workspace Name"; private static final String TEST_LOCALE_NAME = "Test Locale Name"; private static final String TEST_WINDOW_TITLE = "Test Window Title"; private static final String WORKSPACE_TITLE_QUERY_PARAMETER_KEY = "title"; private static final String NO_DOCUMENTS_STRING = "No document selected"; private static final String TEST_DOCUMENT_NAME = "test_document_name"; private static final String TEST_DOCUMENT_PATH = "test/document/path/"; private static final String TEST_WORKSPACE_TITLE = "test workspace title"; private AppPresenter appPresenter; private Display mockDisplay; private DocumentListPresenter mockDocumentListPresenter; private HasClickHandlers mockDocumentsLink; private EventBus mockEventBus; private History mockHistory; private Identity mockIdentity; private HasClickHandlers mockLeaveWorkspaceLink; private WebTransMessages mockMessages; private Person mockPerson; private HasClickHandlers mockSignoutLink; private TranslationPresenter mockTranslationPresenter; private Window mockWindow; private Window.Location mockWindowLocation; private WorkspaceContext mockWorkspaceContext; private Capture<NotificationEventHandler> capturedNotificationEventHandler; private Capture<DocumentStatsUpdatedEventHandler> capturedDocumentStatsUpdatedEventHandler; private Capture<ProjectStatsUpdatedEventHandler> capturedProjectStatsUpdatedEventHandler; private Capture<ClickHandler> capturedLeaveWorkspaceLinkClickHandler; private Capture<ClickHandler> capturedSignoutLinkClickHandler; private Capture<ValueChangeHandler<String>> capturedHistoryValueChangeHandler; private Capture<ClickHandler> capturedDocumentLinkClickHandler; private Capture<DocumentSelectionEvent> capturedDocumentSelectionEvent; private Capture<String> capturedHistoryTokenString; private DocumentInfo testDocInfo; private DocumentId testDocId; private TranslationStats testDocStats; private TranslationStats emptyProjectStats; @BeforeClass public void createMocks() { mockDisplay = createMock(AppPresenter.Display.class); mockDocumentListPresenter = createMock(DocumentListPresenter.class); mockDocumentsLink = createMock(HasClickHandlers.class); mockEventBus = createMock(EventBus.class); mockHistory = createMock(History.class); mockIdentity = createMock(Identity.class); mockMessages = createMock(WebTransMessages.class); mockPerson = createMock(Person.class); mockTranslationPresenter = createMock(TranslationPresenter.class); mockWindow = createMock(Window.class); mockWindowLocation = createMock(Window.Location.class); mockWorkspaceContext = createMock(WorkspaceContext.class); mockLeaveWorkspaceLink = createMock(HasClickHandlers.class); mockSignoutLink = createMock(HasClickHandlers.class); } private AppPresenter newAppPresenter() { return new AppPresenter(mockDisplay, mockEventBus, mockTranslationPresenter, mockDocumentListPresenter, mockIdentity, mockWorkspaceContext, mockMessages, mockHistory, mockWindow, mockWindowLocation); } // Note: unable to test 'sign out' and 'close window' links as these have // static method calls to Application // TODO test that initial history state is handled properly @Test public void performsRequiredActionsOnBind() { resetAllMocks(); setupDefaultMockExpectations(); // default mock expectations include: // - bind doclistpresenter // - bind translationpresenter // - show documents view initially // - set user label // - set workspace name + title // - set window title // - show 'No document selected' // - show (intitially empty) project stats replayAllMocks(); appPresenter = newAppPresenter(); appPresenter.bind(); verifyAllMocks(); } @Test public void showsNotificationEvents() { setupAndBindAppPresenter(); verifyAllMocks(); reset(mockDisplay); String testMessage = "test notification message"; mockDisplay.setNotificationMessage(testMessage); expectLastCall().once(); replay(mockDisplay); NotificationEvent notification = new NotificationEvent(Severity.Info, testMessage); capturedNotificationEventHandler.getValue().onNotification(notification); verify(mockDisplay); } @Test public void showsUpdatedProjectStats() { setupAndBindAppPresenter(); verifyAllMocks(); reset(mockDisplay); Capture<TranslationStats> capturedTranslationStats = new Capture<TranslationStats>(); mockDisplay.setStats(and(capture(capturedTranslationStats), isA(TranslationStats.class))); expectLastCall().once(); replay(mockDisplay); TranslationStats testStats = new TranslationStats(new TransUnitCount(6, 5, 4), new TransUnitWords(3, 2, 1)); ProjectStatsUpdatedEvent event = new ProjectStatsUpdatedEvent(testStats); capturedProjectStatsUpdatedEventHandler.getValue().onProjectStatsRetrieved(event); verify(mockDisplay); assertThat(capturedTranslationStats.getValue(), is(equalTo(testStats))); } @Test public void updateProjectStatsFromEditorView() { setupAndBindAppPresenter(); verifyAllMocks(); HistoryToken token = loadDocAndViewEditor(); reset(mockDisplay); // not expecting stats change yet replay(mockDisplay); TranslationStats updatedStats = new TranslationStats(new TransUnitCount(9, 9, 9), new TransUnitWords(9, 9, 9)); capturedProjectStatsUpdatedEventHandler.getValue().onProjectStatsRetrieved(new ProjectStatsUpdatedEvent(updatedStats)); verify(mockDisplay); returnToDoclistView(token, updatedStats); } @Test public void historyTriggersDocumentSelectionEvent() { setupAndBindAppPresenter(); verifyAllMocks(); reset(mockDisplay, mockDocumentListPresenter); // not testing for specific values for the following in this test mockDisplay.setDocumentLabel(notNull(String.class), notNull(String.class)); expectLastCall().anyTimes(); mockDisplay.setStats(notNull(TranslationStats.class)); expectLastCall().anyTimes(); buildTestDocumentInfo(); expect(mockDocumentListPresenter.getDocumentId(TEST_DOCUMENT_PATH + TEST_DOCUMENT_NAME)).andReturn(testDocId).anyTimes(); expect(mockDocumentListPresenter.getDocumentInfo(testDocId)).andReturn(testDocInfo).anyTimes(); replay(mockDisplay, mockDocumentListPresenter); HistoryToken docSelectionToken = new HistoryToken(); docSelectionToken.setDocumentPath(TEST_DOCUMENT_PATH + TEST_DOCUMENT_NAME); capturedHistoryValueChangeHandler.getValue().onValueChange(new ValueChangeEvent<String>(docSelectionToken.toTokenString()) { }); assertThat("a new document path in history should trigger a document selection event with the correct id", capturedDocumentSelectionEvent.getValue().getDocumentId(), is(testDocId)); } @Test public void historyTriggersViewChange() { setupAndBindAppPresenter(); verifyAllMocks(); reset(mockDisplay, mockDocumentListPresenter); buildTestDocumentInfo(); expect(mockDocumentListPresenter.getDocumentId(TEST_DOCUMENT_PATH + TEST_DOCUMENT_NAME)).andReturn(testDocId).anyTimes(); expect(mockDocumentListPresenter.getDocumentInfo(testDocId)).andReturn(testDocInfo).anyTimes(); mockDisplay.showInMainView(MainView.Editor); expectLastCall().once(); // avoid checking name or stats for this test mockDisplay.setDocumentLabel(notNull(String.class), notNull(String.class)); expectLastCall().anyTimes(); mockDisplay.setStats(notNull(TranslationStats.class)); expectLastCall().anyTimes(); replay(mockDisplay, mockDocumentListPresenter); HistoryToken docInEditorToken = new HistoryToken(); // requires valid selected document to change to editor view docInEditorToken.setDocumentPath(TEST_DOCUMENT_PATH + TEST_DOCUMENT_NAME); docInEditorToken.setView(MainView.Editor); capturedHistoryValueChangeHandler.getValue().onValueChange(new ValueChangeEvent<String>(docInEditorToken.toTokenString()) { }); verify(mockDisplay); } @Test public void noEditorWithoutValidDocument() { setupAndBindAppPresenter(); verifyAllMocks(); reset(mockDisplay, mockDocumentListPresenter); // return invalid document expect(mockDocumentListPresenter.getDocumentId(notNull(String.class))).andReturn(null).anyTimes(); replay(mockDisplay, mockDocumentListPresenter); HistoryToken editorWithoutDocToken = new HistoryToken(); editorWithoutDocToken.setView(MainView.Editor); capturedHistoryValueChangeHandler.getValue().onValueChange(new ValueChangeEvent<String>(editorWithoutDocToken.toTokenString()) { }); // not expecting show view editor verify(mockDisplay); } @Test public void historyTriggersDocumentNameStatsUpdate() { setupAndBindAppPresenter(); verifyAllMocks(); reset(mockDisplay, mockDocumentListPresenter); buildTestDocumentInfo(); expect(mockDocumentListPresenter.getDocumentId(TEST_DOCUMENT_PATH + TEST_DOCUMENT_NAME)).andReturn(testDocId).anyTimes(); expect(mockDocumentListPresenter.getDocumentInfo(testDocId)).andReturn(testDocInfo).anyTimes(); // avoid checking for view change, tested elsewhere mockDisplay.showInMainView(isA(MainView.class)); expectLastCall().anyTimes(); mockDisplay.setDocumentLabel(TEST_DOCUMENT_PATH, TEST_DOCUMENT_NAME); expectLastCall().once(); mockDisplay.setStats(eq(testDocStats)); expectLastCall().once(); replay(mockDisplay, mockDocumentListPresenter); HistoryToken docInEditorToken = new HistoryToken(); docInEditorToken.setView(MainView.Editor); docInEditorToken.setDocumentPath(TEST_DOCUMENT_PATH + TEST_DOCUMENT_NAME); capturedHistoryValueChangeHandler.getValue().onValueChange(new ValueChangeEvent<String>(docInEditorToken.toTokenString()) { }); verify(mockDisplay); } /** * Note: this also verifies that editor pending change is saved when changing * from editor to document list */ @Test public void statsAndNameChangeWithView() { setupAndBindAppPresenter(); verifyAllMocks(); HistoryToken token = loadDocAndViewEditor(); token = returnToDoclistView(token, emptyProjectStats); returnToEditorView(token, testDocStats); } @Test public void showsUpdatedDocumentStats() { setupAndBindAppPresenter(); verifyAllMocks(); // must be in editor to see document stats loadDocAndViewEditor(); TranslationStats updatedStats = new TranslationStats(new TransUnitCount(9, 9, 9), new TransUnitWords(9, 9, 9)); reset(mockDisplay); mockDisplay.setStats(eq(updatedStats)); expectLastCall().once(); replay(mockDisplay); capturedDocumentStatsUpdatedEventHandler.getValue().onDocumentStatsUpdated(new DocumentStatsUpdatedEvent(testDocId, updatedStats)); verify(mockDisplay); } @Test public void doesNotShowWrongDocumentStats() { setupAndBindAppPresenter(); verifyAllMocks(); loadDocAndViewEditor(); TranslationStats updatedStats = new TranslationStats(new TransUnitCount(9, 9, 9), new TransUnitWords(9, 9, 9)); reset(mockDisplay); // not expecting stats change replay(mockDisplay); DocumentId notSelectedDocId = new DocumentId(7777L); capturedDocumentStatsUpdatedEventHandler.getValue().onDocumentStatsUpdated(new DocumentStatsUpdatedEvent(notSelectedDocId, updatedStats)); verify(mockDisplay); } @Test public void updateDocumentStatsFromDoclistView() { setupAndBindAppPresenter(); verifyAllMocks(); HistoryToken token = loadDocAndViewEditor(); token = returnToDoclistView(token, emptyProjectStats); reset(mockDisplay); // not expecting stats change yet replay(mockDisplay); TranslationStats updatedStats = new TranslationStats(new TransUnitCount(9, 9, 9), new TransUnitWords(9, 9, 9)); capturedDocumentStatsUpdatedEventHandler.getValue().onDocumentStatsUpdated(new DocumentStatsUpdatedEvent(testDocId, updatedStats)); verify(mockDisplay); returnToEditorView(token, updatedStats); } @Test public void documentsLinkGeneratesHistoryToken() { setupAndBindAppPresenter(); verifyAllMocks(); ClickEvent docLinkClickEvent = createMock(ClickEvent.class); // replay(docLinkClickEvent); // don't generate MainView.Editor token if a document isn't loaded capturedDocumentLinkClickHandler.getValue().onClick(docLinkClickEvent); assertThat(capturedHistoryTokenString.hasCaptured(), is(false)); HistoryToken token = loadDocAndViewEditor(); // make mock history return correct state reset(mockHistory); expect(mockHistory.getToken()).andReturn(token.toTokenString()).anyTimes(); mockHistory.newItem(capture(capturedHistoryTokenString)); expectLastCall().anyTimes(); replay(mockHistory); capturedDocumentLinkClickHandler.getValue().onClick(docLinkClickEvent); // should have token with doclist view HistoryToken capturedToken = HistoryToken.fromTokenString(capturedHistoryTokenString.getValue()); assertThat("clicking documents link should always show doclist when editor is visible", capturedToken.getView(), is(MainView.Documents)); assertThat("document path should be maintained when clicking documents link", capturedToken.getDocumentPath(), is(token.getDocumentPath())); // TODO could check that filter parameters haven't changed as well token = returnToDoclistView(token, emptyProjectStats); // make mock history return correct state reset(mockHistory); expect(mockHistory.getToken()).andReturn(token.toTokenString()).anyTimes(); mockHistory.newItem(capture(capturedHistoryTokenString)); expectLastCall().anyTimes(); replay(mockHistory); capturedDocumentLinkClickHandler.getValue().onClick(docLinkClickEvent); // should have token with editor view capturedToken = HistoryToken.fromTokenString(capturedHistoryTokenString.getValue()); assertThat("clicking documents link should show editor when doclist is visible and a valid document is selected", capturedToken.getView(), is(MainView.Editor)); assertThat("document path should be maintained when clicking documents link", capturedToken.getDocumentPath(), is(token.getDocumentPath())); } /** * generates new test doc id and doc info ready for use in tests */ private void buildTestDocumentInfo() { testDocId = new DocumentId(2222L); TransUnitCount unitCount = new TransUnitCount(1, 2, 3); TransUnitWords wordCount = new TransUnitWords(4, 5, 6); testDocStats = new TranslationStats(unitCount, wordCount); testDocInfo = new DocumentInfo(testDocId, TEST_DOCUMENT_NAME, TEST_DOCUMENT_PATH, testDocStats); } /** * Simulate selecting test document and viewing it in the editor. The * application presenter must be bound before calling this method. * * This also tests that: * <ul> * <li>A history event with a valid document will correctly display the * editor view.</li> * <li>The document path, name and stats are displayed in the editor.</li> * </ul> * * @return a {@link HistoryToken} representing the current application state */ private HistoryToken loadDocAndViewEditor() { reset(mockDisplay, mockDocumentListPresenter); buildTestDocumentInfo(); expect(mockDocumentListPresenter.getDocumentId(TEST_DOCUMENT_PATH + TEST_DOCUMENT_NAME)).andReturn(testDocId).anyTimes(); expect(mockDocumentListPresenter.getDocumentInfo(testDocId)).andReturn(testDocInfo).anyTimes(); // test document name and stats should be shown mockDisplay.setDocumentLabel(TEST_DOCUMENT_PATH, TEST_DOCUMENT_NAME); expectLastCall().anyTimes(); mockDisplay.setStats(eq(testDocStats)); expectLastCall().anyTimes(); mockDisplay.showInMainView(MainView.Editor); expectLastCall().once(); replay(mockDisplay, mockDocumentListPresenter); HistoryToken docInEditorToken = new HistoryToken(); docInEditorToken.setDocumentPath(TEST_DOCUMENT_PATH + TEST_DOCUMENT_NAME); docInEditorToken.setView(MainView.Editor); capturedHistoryValueChangeHandler.getValue().onValueChange(new ValueChangeEvent<String>(docInEditorToken.toTokenString()) { }); verify(mockDisplay, mockDocumentListPresenter); return docInEditorToken; } /** * @param previousToken a token representing the state of the application * before returning to document list view * * @return a {@link HistoryToken} representing the current application state */ private HistoryToken returnToDoclistView(HistoryToken previousToken, TranslationStats currentProjectStats) { // return to doc list reset(mockDisplay, mockTranslationPresenter); mockDisplay.showInMainView(MainView.Documents); expectLastCall().once(); mockDisplay.setDocumentLabel("", NO_DOCUMENTS_STRING); expectLastCall().once(); // project stats are empty in default test setup mockDisplay.setStats(eq(currentProjectStats)); expectLastCall().once(); mockTranslationPresenter.saveEditorPendingChange(); expectLastCall().once(); replay(mockDisplay, mockTranslationPresenter); previousToken.setView(MainView.Documents); capturedHistoryValueChangeHandler.getValue().onValueChange(new ValueChangeEvent<String>(previousToken.toTokenString()) { }); return previousToken; // updated } /** * Return to the editor view with the test document already loaded * * @param previousToken a token representing the state of the application * before returning to the editor view */ private void returnToEditorView(HistoryToken previousToken, TranslationStats expectedStats) { // return to editor reset(mockDisplay); mockDisplay.showInMainView(MainView.Editor); expectLastCall().once(); mockDisplay.setDocumentLabel(TEST_DOCUMENT_PATH, TEST_DOCUMENT_NAME); expectLastCall().once(); mockDisplay.setStats(eq(expectedStats)); expectLastCall().once(); replay(mockDisplay); previousToken.setView(MainView.Editor); capturedHistoryValueChangeHandler.getValue().onValueChange(new ValueChangeEvent<String>(previousToken.toTokenString()) { }); } private void setupAndBindAppPresenter() { resetAllMocks(); setupDefaultMockExpectations(); replayAllMocks(); appPresenter = newAppPresenter(); appPresenter.bind(); } private void setupDefaultMockExpectations() { expect(mockDisplay.getSignOutLink()).andReturn(mockSignoutLink).anyTimes(); expect(mockDisplay.getLeaveWorkspaceLink()).andReturn(mockLeaveWorkspaceLink).anyTimes(); expect(mockDisplay.getDocumentsLink()).andReturn(mockDocumentsLink).anyTimes(); mockDisplay.showInMainView(MainView.Documents); expectLastCall().anyTimes(); mockDisplay.setDocumentLabel("", NO_DOCUMENTS_STRING); expectLastCall().once(); mockDisplay.setUserLabel(TEST_PERSON_NAME); expectLastCall().anyTimes(); mockDisplay.setWorkspaceNameLabel(TEST_WORKSPACE_NAME, TEST_WORKSPACE_TITLE); expectLastCall().anyTimes(); // initially empty project stats emptyProjectStats = new TranslationStats(); mockDisplay.setStats(eq(emptyProjectStats)); expectLastCall().once(); mockDocumentListPresenter.bind(); expectLastCall().once(); capturedDocumentLinkClickHandler = new Capture<ClickHandler>(); expect(mockDocumentsLink.addClickHandler(and(capture(capturedDocumentLinkClickHandler), isA(ClickHandler.class)))).andReturn(createMock(HandlerRegistration.class)).once(); capturedNotificationEventHandler = new Capture<NotificationEventHandler>(); expect(mockEventBus.addHandler(eq(NotificationEvent.getType()), and(capture(capturedNotificationEventHandler), isA(NotificationEventHandler.class)))).andReturn(createMock(HandlerRegistration.class)).once(); capturedDocumentStatsUpdatedEventHandler = new Capture<DocumentStatsUpdatedEventHandler>(); expect(mockEventBus.addHandler(eq(DocumentStatsUpdatedEvent.getType()), and(capture(capturedDocumentStatsUpdatedEventHandler), isA(DocumentStatsUpdatedEventHandler.class)))).andReturn(createMock(HandlerRegistration.class)).once(); capturedProjectStatsUpdatedEventHandler = new Capture<ProjectStatsUpdatedEventHandler>(); expect(mockEventBus.addHandler(eq(ProjectStatsUpdatedEvent.getType()), and(capture(capturedProjectStatsUpdatedEventHandler), isA(ProjectStatsUpdatedEventHandler.class)))).andReturn(createMock(HandlerRegistration.class)).once(); capturedDocumentSelectionEvent = new Capture<DocumentSelectionEvent>(); mockEventBus.fireEvent(and(capture(capturedDocumentSelectionEvent), isA(DocumentSelectionEvent.class))); expectLastCall().anyTimes(); setupMockHistory(""); expect(mockIdentity.getPerson()).andReturn(mockPerson).anyTimes(); capturedLeaveWorkspaceLinkClickHandler = new Capture<ClickHandler>(); expect(mockLeaveWorkspaceLink.addClickHandler(and(capture(capturedLeaveWorkspaceLinkClickHandler), isA(ClickHandler.class)))).andReturn(createMock(HandlerRegistration.class)).once(); expect(mockMessages.windowTitle(TEST_WORKSPACE_NAME, TEST_LOCALE_NAME)).andReturn(TEST_WINDOW_TITLE).anyTimes(); expect(mockMessages.noDocumentSelected()).andReturn(NO_DOCUMENTS_STRING).anyTimes(); expect(mockPerson.getName()).andReturn(TEST_PERSON_NAME).anyTimes(); capturedSignoutLinkClickHandler = new Capture<ClickHandler>(); expect(mockSignoutLink.addClickHandler(and(capture(capturedSignoutLinkClickHandler), isA(ClickHandler.class)))).andReturn(createMock(HandlerRegistration.class)).once(); mockTranslationPresenter.bind(); expectLastCall().once(); mockWindow.setTitle(TEST_WINDOW_TITLE); expectLastCall().once(); expect(mockWindowLocation.getParameter(WORKSPACE_TITLE_QUERY_PARAMETER_KEY)).andReturn(TEST_WORKSPACE_TITLE).anyTimes(); expect(mockWorkspaceContext.getWorkspaceName()).andReturn(TEST_WORKSPACE_NAME).anyTimes(); expect(mockWorkspaceContext.getLocaleName()).andReturn(TEST_LOCALE_NAME).anyTimes(); } @SuppressWarnings("unchecked") private void setupMockHistory(String tokenToReturn) { capturedHistoryValueChangeHandler = new Capture<ValueChangeHandler<String>>(); expect(mockHistory.addValueChangeHandler(and(capture(capturedHistoryValueChangeHandler), isA(ValueChangeHandler.class)))).andReturn(createMock(HandlerRegistration.class)).anyTimes(); expect(mockHistory.getToken()).andReturn(tokenToReturn).anyTimes(); mockHistory.fireCurrentHistoryState(); expectLastCall().anyTimes(); capturedHistoryTokenString = new Capture<String>(); mockHistory.newItem(capture(capturedHistoryTokenString)); expectLastCall().anyTimes(); } private void resetAllMocks() { reset(mockDisplay, mockDocumentListPresenter, mockDocumentsLink); reset(mockEventBus, mockHistory, mockIdentity, mockLeaveWorkspaceLink); reset(mockMessages, mockPerson, mockSignoutLink, mockTranslationPresenter); reset(mockWindow, mockWindowLocation, mockWorkspaceContext); } private void replayAllMocks() { replay(mockDisplay, mockDocumentListPresenter, mockDocumentsLink); replay(mockEventBus, mockHistory, mockIdentity, mockLeaveWorkspaceLink); replay(mockMessages, mockPerson, mockSignoutLink, mockTranslationPresenter); replay(mockWindow, mockWindowLocation, mockWorkspaceContext); } private void verifyAllMocks() { verify(mockDisplay, mockDocumentListPresenter, mockDocumentsLink); verify(mockEventBus, mockHistory, mockIdentity, mockLeaveWorkspaceLink); verify(mockMessages, mockPerson, mockSignoutLink, mockTranslationPresenter); verify(mockWindow, mockWindowLocation, mockWorkspaceContext); } }
package com.java110.api.listener.fee; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.java110.api.bmo.tempCarFeeConfig.ITempCarFeeConfigBMO; import com.java110.api.bmo.tempCarFeeConfigAttr.ITempCarFeeConfigAttrBMO; import com.java110.api.listener.AbstractServiceApiPlusListener; import com.java110.core.annotation.Java110Listener; import com.java110.core.context.DataFlowContext; import com.java110.core.event.service.api.ServiceDataFlowEvent; import com.java110.utils.constant.ServiceCodeTempCarFeeConfigConstant; import com.java110.utils.util.Assert; import com.java110.utils.util.StringUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; /** * * add by wuxw 2019-06-30 */ @Java110Listener("deleteTempCarFeeConfigListener") public class DeleteTempCarFeeConfigListener extends AbstractServiceApiPlusListener { @Autowired private ITempCarFeeConfigBMO tempCarFeeConfigBMOImpl; @Autowired private ITempCarFeeConfigAttrBMO tempCarFeeConfigAttrBMOImpl; @Override protected void validate(ServiceDataFlowEvent event, JSONObject reqJson) { //Assert.hasKeyAndValue(reqJson, "xxx", "xxx"); Assert.hasKeyAndValue(reqJson, "configId", "configId"); Assert.hasKeyAndValue(reqJson, "communityId", "ID"); } @Override protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) { tempCarFeeConfigBMOImpl.deleteTempCarFeeConfig(reqJson, context); JSONArray attrs = reqJson.getJSONArray("attrs"); if (attrs.size() < 1) { return; } JSONObject attr = null; for (int attrIndex = 0; attrIndex < attrs.size(); attrIndex++) { attr = attrs.getJSONObject(attrIndex); attr.put("ruleId", reqJson.getString("ruleId")); attr.put("communityId", reqJson.getString("communityId")); if (!attr.containsKey("attrId") || attr.getString("attrId").startsWith("-") || StringUtil.isEmpty(attr.getString("attrId"))) { continue; } tempCarFeeConfigAttrBMOImpl.deleteTempCarFeeConfigAttr(attr, context); } } @Override public String getServiceCode() { return ServiceCodeTempCarFeeConfigConstant.DELETE_TEMPCARFEECONFIG; } @Override public HttpMethod getHttpMethod() { return HttpMethod.POST; } }
package fi.nls.oskari.search; import fi.mml.portti.service.search.ChannelSearchResult; import fi.mml.portti.service.search.SearchCriteria; import fi.mml.portti.service.search.SearchResultItem; import fi.nls.oskari.annotation.Oskari; import fi.nls.oskari.domain.geo.Point; import fi.nls.oskari.log.LogFactory; import fi.nls.oskari.log.Logger; import fi.nls.oskari.map.geometry.ProjectionHelper; import fi.nls.oskari.search.channel.SearchChannel; import fi.nls.oskari.util.IOHelper; import fi.nls.oskari.util.JSONHelper; import fi.nls.oskari.util.PropertyUtil; import org.geotools.referencing.CRS; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.opengis.referencing.crs.CoordinateReferenceSystem; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.util.HashMap; import java.util.Map; @Oskari(OpenStreetMapSearchChannel.ID) public class OpenStreetMapSearchChannel extends SearchChannel { /** logger */ private Logger log = LogFactory.getLogger(this.getClass()); private String serviceURL = null; public static final String ID = "OPENSTREETMAP_CHANNEL"; public final static String SERVICE_SRS = "EPSG:4326"; private static final String PROPERTY_SERVICE_URL = "search.channel.OPENSTREETMAP_CHANNEL.service.url"; private static final String PROPERTY_BBOX = "search.channel.OPENSTREETMAP_CHANNEL.search.bbox"; @Override public void init() { super.init(); serviceURL = PropertyUtil.get(PROPERTY_SERVICE_URL, "https://nominatim.openstreetmap.org/search"); log.debug("ServiceURL set to " + serviceURL); } private String getUrl(SearchCriteria searchCriteria) throws UnsupportedEncodingException { Map<String, String> params = new HashMap<>(); params.put("format", "json"); params.put("addressdetails", "1"); String filterBBOX = PropertyUtil.getOptional(PROPERTY_BBOX); if(filterBBOX != null) { params.put("bounded", "1"); params.put("viewbox", filterBBOX); } else { log.debug("Search BBOX not configured. Add property with key", PROPERTY_BBOX); } params.put("accept-language", searchCriteria.getLocale()); int maxResults = getMaxResults(searchCriteria.getMaxResults()); if (maxResults > 0) { params.put("limit", Integer.toString(maxResults) + 1); } params.put("q", searchCriteria.getSearchString()); return IOHelper.constructUrl(serviceURL, params); } /** * Returns the search raw results. * @param searchCriteria Search criteria. * @return Result data in JSON format. * @throws Exception */ private JSONArray getData(SearchCriteria searchCriteria) throws Exception { if (serviceURL == null) { log.warn("ServiceURL not configured. Add property with key", PROPERTY_SERVICE_URL); return new JSONArray(); } String url = getUrl(searchCriteria); HttpURLConnection connection = getConnection(url); IOHelper.addIdentifierHeaders(connection); String data = IOHelper.readString(connection); log.debug("DATA: " + data); return JSONHelper.createJSONArray(data); } /** * Returns the channel search results. * @param searchCriteria Search criteria. * @return Search results. */ public ChannelSearchResult doSearch(SearchCriteria searchCriteria) { ChannelSearchResult searchResultList = new ChannelSearchResult(); String srs = searchCriteria.getSRS(); if( srs == null ) { srs = "EPSG:3067"; } try { // Lon,lat (east coordinate is always first in transformation input and output CoordinateReferenceSystem sourceCrs = CRS.decode(SERVICE_SRS, true); CoordinateReferenceSystem targetCrs = CRS.decode(srs, true); final JSONArray data = getData(searchCriteria); for (int i = 0; i < data.length(); i++) { JSONObject dataItem = data.getJSONObject(i); JSONObject address = dataItem.getJSONObject("address"); SearchResultItem item = new SearchResultItem(); item.setTitle(JSONHelper.getStringFromJSON(dataItem, "display_name", "")); item.setDescription(JSONHelper.getStringFromJSON(dataItem, "display_name", "")); item.setLocationTypeCode(JSONHelper.getStringFromJSON(dataItem, "class", "")); item.setType(JSONHelper.getStringFromJSON(dataItem, "class", "")); item.setRegion(JSONHelper.getStringFromJSON(address, "city", "")); final double lat = dataItem.optDouble("lat"); final double lon = dataItem.optDouble("lon"); // convert to map projection final Point point = ProjectionHelper.transformPoint(lon, lat, sourceCrs, targetCrs); if (point == null) { continue; } item.setLon(point.getLon()); item.setLat(point.getLat()); // FIXME: add more automation on result rank scaling try { item.setRank(100 * (int) Math.round(dataItem.getDouble("importance"))); } catch (JSONException e) { item.setRank(0); } searchResultList.addItem(item); } } catch (Exception e) { log.error(e, "Failed to search locations from register of OpenStreetMap"); } return searchResultList; } }
package de.gurkenlabs.litiengine.util; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Toolkit; import java.awt.Transparency; import java.awt.geom.AffineTransform; import java.awt.geom.Dimension2D; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.FilteredImageSource; import java.awt.image.ImageFilter; import java.awt.image.ImageProducer; import java.awt.image.RGBImageFilter; import java.awt.image.WritableRaster; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import java.util.function.UnaryOperator; import de.gurkenlabs.litiengine.entities.Rotation; import de.gurkenlabs.litiengine.graphics.Spritesheet; import de.gurkenlabs.litiengine.util.geom.GeometricUtilities; public final class Imaging { public static final int CROP_ALIGN_CENTER = 0; public static final int CROP_ALIGN_LEFT = 1; public static final int CROP_ALIGN_RIGHT = 2; public static final int CROP_VALIGN_BOTTOM = 3; public static final int CROP_VALIGN_CENTER = 0; public static final int CROP_VALIGN_TOP = 1; public static final int CROP_VALIGN_TOPCENTER = 2; private static GraphicsConfiguration graphicsConfig; private Imaging() { throw new UnsupportedOperationException(); } /** * Adds a shadow effect by executing the following steps: 1. Transform visible * pixels to a semi-transparent black 2. Flip the image vertically 3. Scale it * down 4. Render original image and shadow on a buffered image * <p> * TODO: Add support for different shadow types. Add an ellipse shadow, similar to the Lepus reatures. * </p> * * @param image * the image * @param xOffset * the x offset * @param yOffset * the y offset * @return the buffered image */ public static BufferedImage addShadow(final BufferedImage image, final int xOffset, final int yOffset) { if (image == null) { return image; } final int width = image.getWidth(); final int height = image.getHeight(); if (width == 0 || height == 0) { return image; } // Transform visible pixels to a semi-transparent black final BufferedImage shadowImage = flashVisiblePixels(image, new Color(0, 0, 0, 30)); if (shadowImage == null) { return image; } final AffineTransform tx = new AffineTransform(); // Flip the image vertically tx.concatenate(AffineTransform.getScaleInstance(1, -0.15)); tx.concatenate(AffineTransform.getTranslateInstance(0, -shadowImage.getHeight())); final AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); final BufferedImage rotatedImage = op.filter(shadowImage, null); final BufferedImage shadow = getCompatibleImage(width, height + rotatedImage.getHeight() * 2); if (shadow == null) { return image; } final Graphics2D g2D = shadow.createGraphics(); g2D.drawImage(rotatedImage, xOffset, yOffset + rotatedImage.getHeight(), null); g2D.drawImage(image, 0, rotatedImage.getHeight(), null); g2D.dispose(); return shadow; } /** * All pixels that have the specified color are rendered transparent. * * @param img * the img * @param color * the color * @return the image */ public static BufferedImage applyAlphaChannel(final BufferedImage img, final Color color) { if (color == null || img == null) { return img; } final ImageFilter filter = new RGBImageFilter() { // the color we are looking for... Alpha bits are set to opaque public final int markerRGB = color.getRGB() | 0xFF000000; @Override public final int filterRGB(final int x, final int y, final int rgb) { if ((rgb | 0xFF000000) == this.markerRGB) { // Mark the alpha bits as zero - transparent return 0x00FFFFFF & rgb; } else { // nothing to do return rgb; } } }; final ImageProducer ip = new FilteredImageSource(img.getSource(), filter); return toBufferedImage(Toolkit.getDefaultToolkit().createImage(ip)); } public static BufferedImage borderAlpha(final BufferedImage image, final Color strokeColor, boolean borderOnly) { final BufferedImage bimage = getCompatibleImage(image.getWidth(null) + 2, image.getHeight(null) + 2); if (bimage == null) { return image; } final BufferedImage strokeImg = flashVisiblePixels(image, strokeColor); // Draw the image on to the buffered image final Graphics2D graphics = bimage.createGraphics(); graphics.drawImage(strokeImg, 0, 1, null); graphics.drawImage(strokeImg, 2, 1, null); graphics.drawImage(strokeImg, 1, 0, null); graphics.drawImage(strokeImg, 1, 2, null); Composite old = graphics.getComposite(); graphics.setComposite(AlphaComposite.Clear); for (int y = 0; y < image.getHeight(); y++) { for (int x = 0; x < image.getWidth(); x++) { final int pixel = image.getRGB(x, y); if (pixel >> 24 != 0x00) { graphics.fillRect(x + 1, y + 1, 1, 1); } } } if (!borderOnly) { graphics.setComposite(old); graphics.drawImage(image, 1, 1, null); } graphics.dispose(); return bimage; } public static boolean isEmpty(final BufferedImage image) { for (int y = 0; y < image.getHeight(); y++) { for (int x = 0; x < image.getWidth(); x++) { final int pixel = image.getRGB(x, y); if (pixel >> 24 != 0x00) { return false; } } } return true; } /** * Crops a sub image from the specified image. * * @param image * The image to crop the sub-image from. * @param cropAlignment * use the following consts: <br> * <ul> * <li>{@link de.gurkenlabs.litiengine.util.Imaging#CROP_ALIGN_CENTER * CROP_ALIGN_CENTER}</li> * <li>{@link de.gurkenlabs.litiengine.util.Imaging#CROP_ALIGN_LEFT * CROP_ALIGN_LEFT}</li> * <li>{@link de.gurkenlabs.litiengine.util.Imaging#CROP_ALIGN_RIGHT * CROP_ALIGN_RIGHT}</li> * </ul> * @param cropVerticlaAlignment * use the following consts: <br> * <ul> * <li>{@link de.gurkenlabs.litiengine.util.Imaging#CROP_VALIGN_CENTER * CROP_VALIGN_CENTER}</li> * <li>{@link de.gurkenlabs.litiengine.util.Imaging#CROP_VALIGN_TOP * CROP_VALIGN_TOP}</li> * <li>{@link de.gurkenlabs.litiengine.util.Imaging#CROP_VALIGN_TOPCENTER * CROP_VALIGN_TOPCENTER}</li> * <li>{@link de.gurkenlabs.litiengine.util.Imaging#CROP_VALIGN_BOTTOM * CROP_VALIGN_BOTTOM}</li> * </ul> * @param width * The width to crop. * @param height * The height to crop. * @return The cropped image or the original image if it is smaller than the * specified dimensions. */ public static BufferedImage crop(final BufferedImage image, final int cropAlignment, final int cropVerticlaAlignment, final int width, final int height) { if (width > image.getWidth() || height > image.getHeight()) { return image; } int x; switch (cropAlignment) { case CROP_ALIGN_CENTER: x = image.getWidth() / 2 - width / 2; break; case CROP_ALIGN_RIGHT: x = image.getWidth() - width; break; case CROP_ALIGN_LEFT: default: x = 0; break; } int y; switch (cropVerticlaAlignment) { case CROP_VALIGN_CENTER: y = image.getHeight() / 2 - height / 2; break; case CROP_VALIGN_BOTTOM: y = image.getHeight() - height; break; case CROP_VALIGN_TOPCENTER: y = image.getHeight() / 2 - height; break; case CROP_VALIGN_TOP: default: y = 0; break; } return image.getSubimage(x, y, width, height); } /** * All pixels that are not transparent are replaced by a pixel of the * specified flashColor. * * @param image * the image * @param flashColor * the flash color * @return the buffered image */ public static BufferedImage flashVisiblePixels(final Image image, final Color flashColor) { final BufferedImage bimage = getCompatibleImage(image.getWidth(null), image.getHeight(null)); if (bimage == null) { return null; } // Draw the image on to the buffered image final Graphics2D bGr = bimage.createGraphics(); bGr.drawImage(image, 0, 0, null); bGr.dispose(); for (int y = 0; y < bimage.getHeight(); y++) { for (int x = 0; x < bimage.getWidth(); x++) { final int pixel = bimage.getRGB(x, y); if (pixel >> 24 != 0x00) { bimage.setRGB(x, y, flashColor.getRGB()); } } } return bimage; } public static BufferedImage flipSpritesHorizontally(final Spritesheet sprite) { return flipSprites(sprite, Imaging::horizontalFlip); } public static BufferedImage flipSpritesVertically(final Spritesheet sprite) { return flipSprites(sprite, Imaging::verticalFlip); } /** * Creates a new <code>BufferedImage</code> instance from the specified image. * * @param image * The image to be copied. * @return A copy of the specified image. */ public static BufferedImage copy(BufferedImage image) { ColorModel cm = image.getColorModel(); boolean isAlphaPremultiplied = cm.isAlphaPremultiplied(); WritableRaster raster = image.copyData(image.getRaster().createCompatibleWritableRaster()); return new BufferedImage(cm, raster, isAlphaPremultiplied, null); } public static BufferedImage getCompatibleImage(final int width, final int height) { if (width == 0 || height == 0) { return null; } if (graphicsConfig == null) { final GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); final GraphicsDevice device = env.getDefaultScreenDevice(); graphicsConfig = device.getDefaultConfiguration(); } return graphicsConfig.createCompatibleImage(width, height, Transparency.TRANSLUCENT); } /** * Gets a two dimensional grid that contains parts of the specified image. * Splits up the specified image into a grid with the defined number of rows and columns. * * @param image * The base image that will be split up. * @param rows * The number of rows. * @param columns * The number or columns. * * @return A two dimensional array with all the sub-images. */ public static BufferedImage[][] getSubImages(final BufferedImage image, final int rows, final int columns) { final BufferedImage[][] smallImages = new BufferedImage[rows][columns]; final int smallWidth = image.getWidth() / columns; final int smallHeight = image.getHeight() / rows; for (int y = 0; y < rows; y++) { for (int x = 0; x < columns; x++) { final int cellX = x * smallWidth; final int cellY = y * smallHeight; smallImages[y][x] = image.getSubimage(cellX, cellY, smallWidth, smallHeight); } } return smallImages; } /** * Flips the specified image horizontally. * * @param img * The image to be flipped. * @return The flipped image. */ public static BufferedImage horizontalFlip(final BufferedImage img) { final int w = img.getWidth(); final int h = img.getHeight(); if (w == 0 || h == 0) { return img; } final BufferedImage dimg = getCompatibleImage(w, h); final Graphics2D g = dimg.createGraphics(); g.drawImage(img, 0, 0, w, h, w, 0, 0, h, null); g.dispose(); return dimg; } /** * Flips the specified image vertically. * * @param img * The image to be flipped. * @return The flipped image. */ public static BufferedImage verticalFlip(final BufferedImage img) { final int w = img.getWidth(); final int h = img.getHeight(); if (w == 0 || h == 0) { return img; } final BufferedImage dimg = getCompatibleImage(w, h); final Graphics2D g = dimg.createGraphics(); g.drawImage(img, 0, 0 + h, w, -h, null); g.dispose(); return dimg; } /** * Replace colors in an image according to a Map containing source colors and target colors, then return the result. * @param bufferedImage the original image * @param colorMappings a Map with source colors as keys and target colors as values * @return a new version of the original image, where the source colors are replaced with the target colors. */ public static BufferedImage replaceColors(final BufferedImage bufferedImage, Map<Color, Color> colorMappings) { BufferedImage recoloredImage = copy(bufferedImage); for (Color originalColor : colorMappings.keySet()) { for (int y = 0; y < recoloredImage.getHeight(); y++) { for (int x = 0; x < recoloredImage.getWidth(); x++) { if (recoloredImage.getRGB(x, y) == originalColor.getRGB()) { int new_clr = colorMappings.get(originalColor).getRGB(); recoloredImage.setRGB(x, y, new_clr); } } } } return recoloredImage; } public static BufferedImage rotate(final BufferedImage bufferedImage, final Rotation rotation) { return rotate(bufferedImage, rotation.getRadians()); } public static BufferedImage rotate(final BufferedImage bufferedImage, final double radians) { double sin = Math.abs(Math.sin(radians)); double cos = Math.abs(Math.cos(radians)); int w = bufferedImage.getWidth(); int h = bufferedImage.getHeight(); int neww = (int) Math.floor(w * cos + h * sin); int newh = (int) Math.floor(h * cos + w * sin); BufferedImage bimg = getCompatibleImage(neww, newh); if (bimg == null) { return bufferedImage; } Graphics2D g = bimg.createGraphics(); g.translate((neww - w) / 2.0, (newh - h) / 2.0); g.rotate(radians, w / 2.0, h / 2.0); g.drawRenderedImage(toBufferedImage(bufferedImage), null); g.dispose(); return bimg; } public static BufferedImage scale(final BufferedImage image, final int max) { Dimension2D newDimension = GeometricUtilities.scaleWithRatio(image.getWidth(), image.getHeight(), max); return scale(image, (int) newDimension.getWidth(), (int) newDimension.getHeight()); } public static BufferedImage scale(final BufferedImage image, final double factor) { return scale(image, factor, false); } public static BufferedImage scale(final BufferedImage image, final double factor, boolean keepRatio) { final double width = image.getWidth(); final double height = image.getHeight(); return scale(image, (int) Math.max(1, Math.round(width * factor)), (int) Math.max(1, Math.round(height * factor)), keepRatio); } /** * The specified image is scaled to a new dimension with the specified width * and height. This method doesn't use anti aliasing for this process to keep * the indy look. * * @param image * the image * @param width * the width * @param height * the height * @return the buffered image */ public static BufferedImage scale(final BufferedImage image, final int width, final int height) { return scale(image, width, height, false); } public static BufferedImage scale(final BufferedImage image, final int width, final int height, final boolean keepRatio) { return scale(image, width, height, keepRatio, true); } public static BufferedImage scale(final BufferedImage image, final int width, final int height, final boolean keepRatio, final boolean fill) { if (width == 0 || height == 0 || image == null) { return null; } final int imageWidth = image.getWidth(); final int imageHeight = image.getHeight(); double newWidth = width; double newHeight = height; if (keepRatio) { final double ratioWidth = image.getWidth() / (double) image.getHeight(); final double ratioHeight = image.getHeight() / (double) image.getWidth(); newHeight = newWidth * ratioHeight; if (newHeight > height) { newHeight = height; newWidth = newHeight * ratioWidth; } } final double scaleX = newWidth / imageWidth; final double scaleY = newHeight / imageHeight; final AffineTransform scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY); final AffineTransformOp bilinearScaleOp = new AffineTransformOp(scaleTransform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); final BufferedImage scaled = bilinearScaleOp.filter(image, getCompatibleImage((int) newWidth, (int) newHeight)); final BufferedImage newImg = getCompatibleImage((int) newWidth, (int) newHeight); if (newImg == null) { return image; } final Graphics2D g = (Graphics2D) newImg.getGraphics(); g.drawImage(scaled, 0, 0, null); g.dispose(); if (fill && (newWidth != width || newHeight != height)) { final BufferedImage wrapperImage = getCompatibleImage(width, height); final Graphics2D g2 = (Graphics2D) wrapperImage.getGraphics(); g2.drawImage(newImg, (int) ((width - newWidth) / 2.0), (int) ((height - newHeight) / 2.0), null); g2.dispose(); return wrapperImage; } return newImg; } public static BufferedImage setOpacity(final Image img, final float opacity) { final BufferedImage bimage = getCompatibleImage(img.getWidth(null), img.getHeight(null)); if (bimage == null) { return null; } // Draw the image on to the buffered image final Graphics2D g2d = bimage.createGraphics(); g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity)); g2d.drawImage(img, 0, 0, null); g2d.dispose(); return bimage; } public static BufferedImage toBufferedImage(final Image img) { if (img == null) { return null; } if (img instanceof BufferedImage) { return (BufferedImage) img; } final BufferedImage bimage = getCompatibleImage(img.getWidth(null), img.getHeight(null)); if (bimage == null) { return null; } final Graphics2D bGr = bimage.createGraphics(); bGr.drawImage(img, 0, 0, null); bGr.dispose(); return bimage; } private static BufferedImage flipSprites(final Spritesheet sprite, UnaryOperator<BufferedImage> flipFunction) { final BufferedImage flippedSprite = Imaging.getCompatibleImage(sprite.getSpriteWidth() * sprite.getColumns(), sprite.getSpriteHeight() * sprite.getRows()); if (flippedSprite == null) { return null; } final Graphics2D g = (Graphics2D) flippedSprite.getGraphics(); int index = 0; for (int column = 0; column < sprite.getColumns(); column++) { for (int row = 0; row < sprite.getRows(); row++) { g.drawImage(flipFunction.apply(sprite.getSprite(index)), column * sprite.getSpriteWidth(), row * sprite.getSpriteHeight(), null); index++; } } g.dispose(); return flippedSprite; } }
package org.hyperic.sigar.cmd; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarPermissionDeniedException; /** * Display all process information. */ public class ProcInfo extends SigarCommandBase { private boolean isSingleProcess; public ProcInfo(Shell shell) { super(shell); } public ProcInfo() { super(); } protected boolean validateArgs(String[] args) { return true; } public String getUsageShort() { return "Display all process info"; } public boolean isPidCompleter() { return true; } public void output(String[] args) throws SigarException { this.isSingleProcess = false; if ((args.length != 0) && args[0].startsWith("-s")) { this.isSingleProcess = true; } if (this.isSingleProcess) { for (int i=1; i<args.length; i++) { try { output(args[i]); } catch (SigarException e) { println("(" + e.getMessage() + ")"); } println("\n } } else { long[] pids = this.shell.findPids(args); for (int i=0; i<pids.length; i++) { try { output(String.valueOf(pids[i])); } catch (SigarPermissionDeniedException e) { println(this.shell.getUserDeniedMessage(pids[i])); } catch (SigarException e) { println("(" + e.getMessage() + ")"); } println("\n } } } public void output(String pid) throws SigarException { println("pid=" + pid); try { println("state=" + sigar.getProcState(pid)); } catch (SigarException e) { if (this.isSingleProcess) { println(e.getMessage()); } } try { println("mem=" + sigar.getProcMem(pid)); } catch (SigarException e) {} try { println("cpu=" + sigar.getProcCpu(pid)); } catch (SigarException e) {} try { println("cred=" + sigar.getProcCred(pid)); } catch (SigarException e) {} try { println("credname=" + sigar.getProcCredName(pid)); } catch (SigarException e) {} } public static void main(String[] args) throws Exception { new ProcInfo().processCommand(args); } }
package dr.inference.operators; import dr.inference.model.Parameter; import dr.inference.prior.ContinuousVariablePrior; import dr.math.MathUtils; import dr.xml.*; /** * A generic operator for use with a single-dimension parameter. * * @author Alexei Drummond * @author Andrew Rambaut * @version $Id: UpDownOperator.java,v 1.25 2005/06/14 10:40:34 rambaut Exp $ */ public class UpDownOperator extends SimpleMCMCOperator implements CoercableMCMCOperator { public static final String UP_DOWN_OPERATOR = "upDownOperator"; public static final String UP = "up"; public static final String DOWN = "down"; public static final String SCALE_FACTOR = "scaleFactor"; public UpDownOperator(Parameter upParameter, Parameter downParameter, double scale, double weight, int mode) { this.upParameter = upParameter; this.downParameter = downParameter; this.scaleFactor = scale; setWeight(weight); this.mode = mode; } public final int getPriorType() { return prior.getPriorType(); } public final double getScaleFactor() { return scaleFactor; } public final void setPriorType(int type) { prior.setPriorType(type); } public final void setScaleFactor(double sf) { if ((sf > 0.0) && (sf < 1.0)) scaleFactor = sf; else throw new IllegalArgumentException("minimum scale must be between 0 and 1"); } /** * change the parameter and return the hastings ratio. */ public final double doOperation() throws OperatorFailedException { int goingUp = (upParameter == null) ? 0 : upParameter.getDimension(); int goingDown = (downParameter == null) ? 0 : downParameter.getDimension(); double scale = (scaleFactor + (MathUtils.nextDouble() * ((1.0 / scaleFactor) - scaleFactor))); double logq = (goingUp - goingDown - 2) * Math.log(scale); if (upParameter != null) { for (int i = 0; i < upParameter.getDimension(); i++) { upParameter.setParameterValue(i, upParameter.getParameterValue(i) * scale); } for (int i = 0; i < upParameter.getDimension(); i++) { if (upParameter.getParameterValue(i) < upParameter.getBounds().getLowerLimit(i) || upParameter.getParameterValue(i) > upParameter.getBounds().getUpperLimit(i)) { throw new OperatorFailedException("proposed value outside boundaries"); } } } if (downParameter != null) { for (int i = 0; i < downParameter.getDimension(); i++) { downParameter.setParameterValue(i, downParameter.getParameterValue(i) / scale); } for (int i = 0; i < downParameter.getDimension(); i++) { if (downParameter.getParameterValue(i) < downParameter.getBounds().getLowerLimit(i) || downParameter.getParameterValue(i) > downParameter.getBounds().getUpperLimit(i)) { throw new OperatorFailedException("proposed value outside boundaries"); } } } return logq; } public final String getPerformanceSuggestion() { double prob = MCMCOperator.Utils.getAcceptanceProbability(this); double targetProb = getTargetAcceptanceProbability(); double sf = OperatorUtils.optimizeScaleFactor(scaleFactor, prob, targetProb); dr.util.NumberFormatter formatter = new dr.util.NumberFormatter(5); if (prob < getMinimumGoodAcceptanceLevel()) { return "Try setting scaleFactor to about " + formatter.format(sf); } else if (prob > getMaximumGoodAcceptanceLevel()) { return "Try setting scaleFactor to about " + formatter.format(sf); } else return ""; } //MCMCOperator INTERFACE public final String getOperatorName() { return (upParameter != null ? "up:" + upParameter.getParameterName() : "") + (downParameter != null ? " down:" + downParameter.getParameterName() : ""); } public double getCoercableParameter() { return Math.log(1.0 / scaleFactor - 1.0) / Math.log(10); } public void setCoercableParameter(double value) { scaleFactor = 1.0 / (Math.pow(10.0, value) + 1.0); } public int getMode() { return mode; } public double getRawParameter() { return scaleFactor; } public double getTargetAcceptanceProbability() { return 0.234; } // Since this operator invariably modifies at least 2 parameters it // should allow lower acceptance probabilities // as it is known that optimal acceptance levels are inversely // proportional to the number of dimensions operated on // AD 16/3/2004 public double getMinimumAcceptanceLevel() { return 0.05; } public double getMaximumAcceptanceLevel() { return 0.3; } public double getMinimumGoodAcceptanceLevel() { return 0.10; } public double getMaximumGoodAcceptanceLevel() { return 0.20; } public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() { public String getParserName() { return UP_DOWN_OPERATOR; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { final double scaleFactor = xo.getDoubleAttribute(SCALE_FACTOR); int mode = CoercableMCMCOperator.DEFAULT; final double weight = xo.getDoubleAttribute(WEIGHT); if (xo.hasAttribute(AUTO_OPTIMIZE)) { if (xo.getBooleanAttribute(AUTO_OPTIMIZE)) { mode = CoercableMCMCOperator.COERCION_ON; } else { mode = CoercableMCMCOperator.COERCION_OFF; } } Parameter param1 = (Parameter) xo.getElementFirstChild(UP); Parameter param2 = (Parameter) xo.getElementFirstChild(DOWN); return new UpDownOperator(param1, param2, scaleFactor, weight, mode); } public String getParserDescription() { return "This element represents an operator that scales two parameters in different directions. " + "Each operation involves selecting a scale uniformly at random between scaleFactor and 1/scaleFactor. " + "The up parameter is multipled by this scale and the down parameter is divided by this scale."; } public Class getReturnType() { return UpDownOperator.class; } public XMLSyntaxRule[] getSyntaxRules() { return rules; } private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ AttributeRule.newDoubleRule(SCALE_FACTOR), AttributeRule.newDoubleRule(WEIGHT), AttributeRule.newBooleanRule(AUTO_OPTIMIZE, true), new ElementRule(UP, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), new ElementRule(DOWN, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}) }; }; //PRIVATE STUFF private Parameter upParameter = null; private Parameter downParameter = null; private ContinuousVariablePrior prior = new ContinuousVariablePrior(); private double scaleFactor = 0.5; private int mode = CoercableMCMCOperator.DEFAULT; }
package edu.cmu.ri.airboat.server; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import com.google.code.microlog4android.LoggerFactory; import org.json.JSONException; import org.json.JSONObject; import java.io.PrintWriter; import java.util.Arrays; import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicBoolean; import edu.cmu.ri.crw.AbstractVehicleServer; import edu.cmu.ri.crw.VehicleController; import edu.cmu.ri.crw.VehicleFilter; import edu.cmu.ri.crw.VehicleServer; import edu.cmu.ri.crw.data.SensorData; import edu.cmu.ri.crw.data.Twist; import edu.cmu.ri.crw.data.Utm; import edu.cmu.ri.crw.data.UtmPose; import robotutils.Pose3D; /** * Contains the actual implementation of vehicle functionality, accessible as a * singleton that is updated and maintained by a background service. * * @author pkv * @author kss * */ public class AirboatImpl extends AbstractVehicleServer { private static final com.google.code.microlog4android.Logger logger = LoggerFactory .getLogger(); private static final String logTag = AirboatImpl.class.getName(); public static final int UPDATE_INTERVAL_MS = 100; public static final int NUM_SENSORS = 4; public static final VehicleController DEFAULT_CONTROLLER = AirboatController.STOP.controller; // public static final VehicleController DEFAULT_CONTROLLER = AirboatController.SHOOT_ON_MOVE; protected final SharedPreferences _prefs; protected final SensorType[] _sensorTypes = new SensorType[NUM_SENSORS]; protected UtmPose[] _waypoints = new UtmPose[0]; protected final Object _captureLock = new Object(); protected TimerTask _captureTask = null; protected final Object _navigationLock = new Object(); protected TimerTask _navigationTask = null; private final Timer _updateTimer = new Timer(); private final Timer _navigationTimer = new Timer(); private final Timer _captureTimer = new Timer(); // TODO: Remove this variable, it is totally arbitrary private double winch_depth_ = Double.NaN; // Conversion to metres for sonar depth private static final double FEET2METRES = 0.3048; public enum VehicleType { DIFFERENTIAL_THRUST, VECTORED_THRUST, UNKNOWN } /** * Defines the PID gains that will be returned if there is an error. */ public static final double[] NAN_GAINS = new double[] { Double.NaN, Double.NaN, Double.NaN }; // Status information final AtomicBoolean _isConnected = new AtomicBoolean(true); final AtomicBoolean _isAutonomous = new AtomicBoolean(false); // Internal data structures for Amarino callbacks final Context _context; final PrintWriter _usbWriter; public static final double[] DEFAULT_TWIST = {0, 0, 0, 0, 0, 0}; /** * Inertial state vector, currently containing a 6D pose estimate: * [x,y,z,roll,pitch,yaw] */ UtmPose _utmPose = new UtmPose(new Pose3D(476608.34, 4671214.40, 172.35, 0, 0, 0), new Utm(17, true)); /** * Filter used internally to update the current pose estimate */ VehicleFilter filter = new SimpleFilter(); /** * Inertial velocity vector, containing a 6D angular velocity estimate: [rx, * ry, rz, rPhi, rPsi, rOmega] */ Twist _velocities = new Twist(DEFAULT_TWIST); /** * Raw gyroscopic readings from the phone gyro. */ final double[] _gyroPhone = new double[3]; /** * Hard-coded PID gains and thrust limits per vehicle type. */ double[] r_PID = {.2, 0, .3}; // Kp, Ki, Kd double [] t_PID = {.7, .5, .5}; public static final double SAFE_DIFFERENTIAL_THRUST = 0.14; public static final double SAFE_VECTORED_THRUST = 0.7; /** * Simple clipping function that restricts a value to a given range. * @param input value that needs to be clipped * @param min minimum allowable value * @param max maximum allowable value * @return value after it has been clipped between min and max. */ public static double clip(double input, double min, double max) { return Math.min(Math.max(input, min), max); } /** * Simple linear scaling function that maps a value from a given input range to a desired output range. * * This does *not* clip out of range values. To invert values, swap min and max. * * @param input value that needs to be scaled * @param input_min lower bound of original mapping * @param input_max upper bound of original mapping * @param output_min lower bound of desired mapping * @param output_max upper bound of desired mapping. * @return the input value mapped into the output range. */ public static double map(double input, double input_min, double input_max, double output_min, double output_max) { return (input - input_min) / (input_max - input_min) * (output_max - output_min) + output_min; } /** * Creates a new instance of the vehicle implementation. This function * should only be used internally when the corresponding vehicle service is * started and stopped. * * @param context * the application context to use * @param usbWriter * the USB device for the vehicle controller */ protected AirboatImpl(Context context, PrintWriter usbWriter) { _context = context; _usbWriter = usbWriter; // Connect to the Shared Preferences for this process. _prefs = PreferenceManager.getDefaultSharedPreferences(_context); // Start a regular update function _updateTimer.scheduleAtFixedRate(_updateTask, 0, UPDATE_INTERVAL_MS); } /** * Internal update function called at regular intervals to process command * and control events. */ private TimerTask _updateTask = new TimerTask() { @Override public void run() { /* * // Compute the number of milliseconds since last update // (or 0 * if this is the first update) long currentUpdateMs = * SystemClock.elapsedRealtime(); long elapsedMs = (_lastUpdateMs > * 0) ? currentUpdateMs - _lastUpdateMs : 0; _lastUpdateMs = * currentUpdateMs; */ // Do an intelligent state prediction update here _utmPose = filter.pose(System.currentTimeMillis()); logger.info("POSE: " + _utmPose); sendState(_utmPose.clone()); // Determine current vehicle type from ordinal value. int vehicle_type_index = _prefs.getInt(AirboatActivity.KEY_VEHICLE_TYPE, VehicleType.UNKNOWN.ordinal()); VehicleType vehicle_type = VehicleType.values()[vehicle_type_index]; // Send vehicle command by converting raw command to appropriate vehicle model. JSONObject command = new JSONObject(); switch (vehicle_type) { case DIFFERENTIAL_THRUST: // Construct objects to hold velocities JSONObject velocity0 = new JSONObject(); JSONObject velocity1 = new JSONObject(); // Send velocities as a JSON command try { // Until ESCs are able to reverse, set the lower limit to 0.0 double constrainedV0 = clip(_velocities.dx() - _velocities.drz(), -1.0, 1.0); double constrainedV1 = clip(_velocities.dx() + _velocities.drz(), -1.0, 1.0); // Until ESC reboot is fixed, set the upper limit to SAFE_THRUST constrainedV0 = map(constrainedV0, -1.0, 1.0, // Original range. -AirboatImpl.SAFE_DIFFERENTIAL_THRUST, AirboatImpl.SAFE_DIFFERENTIAL_THRUST); // New range. constrainedV1 = map(constrainedV1, -1.0, 1.0, // Original range. -AirboatImpl.SAFE_DIFFERENTIAL_THRUST, AirboatImpl.SAFE_DIFFERENTIAL_THRUST); // New range. velocity0.put("v", (float) constrainedV0); velocity1.put("v", (float) constrainedV1); command.put("m0", velocity0); command.put("m1", velocity1); _usbWriter.println(command.toString()); _usbWriter.flush(); logger.info("CMD: " + command.toString()); } catch (JSONException e) { Log.w(logTag, "Failed to serialize command.", e); // TODO: remove this. } break; case VECTORED_THRUST: // Construct objects to hold velocities JSONObject thrust = new JSONObject(); JSONObject rudder = new JSONObject(); // Send velocities as a JSON command try { // Until ESCs are able to reverse, set the lower limit to 0.0 double constrainedV = clip(_velocities.dx(), 0.0, 1.0); // Until ESC reboot is fixed, set the upper limit to SAFE_THRUST constrainedV = map(constrainedV, 0.0, 1.0, // Original range. 0.0, AirboatImpl.SAFE_VECTORED_THRUST); // New range. // Rudder is constrained to +/-1.0 double constrainedP = clip(_velocities.drz(), -1.0, 1.0); thrust.put("v", (float) constrainedV); rudder.put("p", (float) constrainedP); command.put("m0", thrust); command.put("s0", rudder); _usbWriter.println(command.toString()); _usbWriter.flush(); logger.info("CMD: " + command.toString()); } catch (JSONException e) { Log.w(logTag, "Failed to serialize command.", e); // TODO: remove this. } break; default: Log.w(logTag, "Unknown vehicle type: " + vehicle_type); } } }; /** * @see VehicleServer#getGains(int) */ @Override public double[] getGains(int axis) { if (axis == 5) return r_PID.clone(); else if (axis == 0) return t_PID.clone(); else if (axis == 3) return new double[]{ winch_depth_, 0.0, 0.0 }; else return NAN_GAINS; } /** * @see VehicleServer#setGains(int, double[]) */ @Override public void setGains(int axis, double[] k) { if (axis == 5) { r_PID = k.clone(); logger.info("SETGAINS: " + axis + " " + Arrays.toString(k)); } else if (axis == 0) { t_PID = k.clone(); logger.info("SETGAINS: " + axis + " " + Arrays.toString(k)); } // TODO: Get rid of this, it is a hack. // Special case to handle winch commands... else if (axis == 3) { JSONObject command = new JSONObject(); JSONObject winchSettings = new JSONObject(); logger.info("WINCH: " + Arrays.toString(k)); // Call command to adjust winch synchronized (_usbWriter) { try { //Set desired winch movement distance winchSettings.put("p", (float) Math.abs(k[0])); //Hardcoded velocity - get rid of this eventually winchSettings.put("v", 500 * Math.signum(k[0])); command.put("s2", winchSettings); _usbWriter.println(command.toString()); _usbWriter.flush(); logger.info("WINCH CMD: " + command.toString()); } catch (Exception e) { Log.w(logTag, "Unable to construct JSON string from winch command: " + Arrays.toString(k)); } } } } /** * Returns the current gyro readings */ public double[] getGyro() { return _gyroPhone.clone(); } public void setPhoneGyro(float[] gyroValues) { for (int i = 0; i < gyroValues.length; i++) _gyroPhone[i] = (double) gyroValues[i]; } /** * @see edu.cmu.ri.crw.VehicleServer#isConnected() */ public boolean isConnected() { return _isConnected.get(); } /** * Internal function used to set the connection status of this object * (indicating whether currently in contact with vehicle controller). */ protected void setConnected(boolean isConnected) { _isConnected.set(isConnected); } /** * Handles complete Arduino commands, once they are reassembled. * * @param cmd * the list of arguments composing a command */ protected void onCommand(JSONObject cmd) { @SuppressWarnings("unchecked") Iterator<String> keyIterator = cmd.keys(); // Iterate through JSON fields while (keyIterator.hasNext()) { String name = keyIterator.next(); try { JSONObject value = cmd.getJSONObject(name); logger.info("Value" + value + " "+ "Name" + name); if (name.startsWith("m")) { int motor = name.charAt(1) - 48; logger.info("MOTOR" + motor + ": " + value.getDouble("v")); } else if (name.startsWith("s")) { int sensor = name.charAt(1) - 48; logger.info("SENSOR" + sensor + ": " + value.toString()); // Hacks to send sensor information if (value.has("type")) { String type = value.getString("type"); //logger.info("Test1" + type); if (type.equalsIgnoreCase("es2")) { //logger.info("Test2"); SensorData reading = new SensorData(); String[] data = value.getString("data").trim().split(" "); reading.channel = sensor; reading.type = SensorType.TE; // double temp = value.getDouble("data"); // String tem = value.getString("data"); //logger.info("Data"+ data[0]+" " + data[1]); reading.data = new double[] { Double.parseDouble(data[0]), Double.parseDouble(data[1]) }; //reading.data = new double[]{5.0,1.5}; sendSensor(sensor, reading); }else if (type.equalsIgnoreCase("atlas")) { SensorData reading = new SensorData(); String[] data = value.getString("data").trim().split(","); reading.channel = sensor; reading.type = SensorType.UNKNOWN; logger.info("Data"+ data); reading.data = new double[] { Double.parseDouble(data[0]), //Double.parseDouble(data[1]) }; sendSensor(sensor, reading); } else if (type.equalsIgnoreCase("hds")) { String nmea = value.getString("nmea"); if (nmea.startsWith("$SDDBT")) { //Depth Below Transducer try { // DBT Specification: DBT,x.x,f,x.x,M,x.x,F*hh // Fields: [0] - DBT string // [1] - Depth in ft // [3] - Depth in m // [5] - Depth in fathoms // NOTE: Switched to feet output on Dec 12 2015 due to limited // (one decimal place) resolution with m. double DO = Double.parseDouble(nmea.split(",")[1]); DO = DO*FEET2METRES; SensorData reading = new SensorData(); reading.type = SensorType.DEPTH; reading.channel = sensor; reading.data = new double[] { DO }; sendSensor(sensor, reading); } catch(Exception e) { Log.w(logTag, "Failed to parse depth reading: " + nmea); } }else if (nmea.startsWith("$SDMTW")){ //Water Temperature try { // MTW Specification: MTW,x.x,C*hh // Fields: [0] - MTW string // [1] - Temp in deg. C double DO = Double.parseDouble(nmea.split(",")[1]); SensorData reading = new SensorData(); reading.type = SensorType.TE; reading.channel = sensor; reading.data = new double[] { DO }; sendSensor(sensor, reading); } catch(Exception e) { Log.w(logTag, "Failed to parse depth reading: " + nmea); } }else if (nmea.startsWith("$SDRMC")){ //GPS }else{ Log.w(logTag, "Unknown NMEA String: " + nmea); } } else if (type.equalsIgnoreCase("winch")) { SensorData reading = new SensorData(); reading.channel = sensor; reading.type = SensorType.UNKNOWN; reading.data = new double[] { value.getDouble("depth") }; sendSensor(sensor, reading); // TODO: Remove this hack to store winch depth winch_depth_ = reading.data[0]; } } } else { Log.w(logTag, "Received unknown param '" + cmd + "'."); } } catch (JSONException e) { Log.w(logTag, "Malformed JSON command '" + cmd + "'.", e); } } } // TODO: Revert capture image to take images // This is a hack to support the water sampler until PID is working again. public synchronized byte[] captureImage(int width, int height) { // Call command to fire sampler synchronized (_usbWriter) { _usbWriter.println("{\"s0\":{ \"sample\": true }"); _usbWriter.flush(); } Log.i(logTag, "Triggering sampler."); logger.info("SMP: NOW"); return new byte[1]; } public synchronized byte[] captureImageInternal(int width, int height) { byte[] bytes = AirboatCameraActivity.takePhoto(_context, width, height); Log.i(logTag, "Sending image [" + bytes.length + "]"); return bytes; } public synchronized boolean saveImage() { AirboatCameraActivity.savePhoto(_context); Log.i(logTag, "Saving image."); return true; } @Override public void startCamera(final int numFrames, final double interval, final int width, final int height) { Log.i(logTag, "Starting capture: " + numFrames + "(" + width + "x" + height + ") frames @ " + interval + "s"); // Create a camera capture task TimerTask newCaptureTask = new TimerTask() { int iFrame = 0; @Override public void run() { synchronized (_captureLock) { // Take a new image and send it out sendImage(captureImageInternal(width, height)); iFrame++; // If we exceed numFrames, we finished if (numFrames > 0 && iFrame >= numFrames) { sendCameraUpdate(CameraState.DONE); this.cancel(); _captureTask = null; } else { sendCameraUpdate(CameraState.CAPTURING); } } } }; synchronized (_captureLock) { // Cancel any previous capture tasks if (_captureTask != null) _captureTask.cancel(); // Schedule this task for execution _captureTask = newCaptureTask; _captureTimer.scheduleAtFixedRate(_captureTask, 0, (long) (interval * 1000.0)); } // Report the new imaging job in the log file logger.info("IMG: " + numFrames + " @ " + interval + "s, " + width + " x " + height); } @Override public void stopCamera() { // Stop the thread that sends out images by terminating its // navigation flag and then removing the reference to the old flag. synchronized (_captureLock) { if (_captureTask != null) { _captureTask.cancel(); _captureTask = null; } } sendCameraUpdate(CameraState.CANCELLED); } @Override public CameraState getCameraStatus() { synchronized (_captureLock) { if (_captureTask != null) { return CameraState.CAPTURING; } else { return CameraState.OFF; } } } @Override public SensorType getSensorType(int channel) { return _sensorTypes[channel]; } @Override public void setSensorType(int channel, SensorType type) { _sensorTypes[channel] = type; } @Override public int getNumSensors() { return NUM_SENSORS; } @Override public UtmPose getPose() { return _utmPose; } /** * Takes a 6D vehicle pose, does appropriate internal computation to change * the current estimate of vehicle state to match the specified pose. Used * for user- or multirobot- pose corrections. * * @param pose * the corrected 6D pose of the vehicle: [x,y,z,roll,pitch,yaw] */ @Override public void setPose(UtmPose pose) { // Change the offset of this vehicle by modifying filter filter.reset(pose, System.currentTimeMillis()); // Copy this pose over the existing value _utmPose = pose.clone(); // Report the new pose in the log file logger.info("POSE: " + _utmPose); } @Override public void startWaypoints(final UtmPose[] waypoints, final String controller) { Log.i(logTag, "Starting waypoints with " + controller + ": " + Arrays.toString(waypoints)); if (controller.equalsIgnoreCase("PRIMITIVES")) { _waypoints = new UtmPose[waypoints.length]; System.arraycopy(waypoints, 0, _waypoints, 0, _waypoints.length); VehicleController vc = AirboatController.valueOf(controller).controller; vc.update(AirboatImpl.this, (double) UPDATE_INTERVAL_MS / 1000.0); } else { // Create a waypoint navigation task TimerTask newNavigationTask = new TimerTask() { final double dt = (double) UPDATE_INTERVAL_MS / 1000.0; // Retrieve the appropriate controller in initializer VehicleController vc = DEFAULT_CONTROLLER; { try { vc = (controller == null) ? vc : AirboatController.valueOf(controller).controller; } catch (IllegalArgumentException e) { Log.w(logTag, "Unknown controller specified (using " + vc + " instead): " + controller); } } @Override public void run() { synchronized (_navigationLock) { if (!_isAutonomous.get()) { // If we are not autonomous, do nothing sendWaypointUpdate(WaypointState.PAUSED); } else if (_waypoints.length == 0) { // If we are finished with waypoints, stop in place sendWaypointUpdate(WaypointState.DONE); setVelocity(new Twist(DEFAULT_TWIST)); this.cancel(); _navigationTask = null; } else { // If we are still executing waypoints, use a // controller to figure out how to get to waypoint // TODO: measure dt directly instead of approximating vc.update(AirboatImpl.this, dt); sendWaypointUpdate(WaypointState.GOING); } } } }; synchronized (_navigationLock) { // Change waypoints to new set of waypoints _waypoints = new UtmPose[waypoints.length]; System.arraycopy(waypoints, 0, _waypoints, 0, _waypoints.length); // Cancel any previous navigation tasks if (_navigationTask != null) _navigationTask.cancel(); // Schedule this task for execution _navigationTask = newNavigationTask; _navigationTimer.scheduleAtFixedRate(_navigationTask, 0, UPDATE_INTERVAL_MS); } // Report the new waypoint in the log file logger.info("NAV: " + controller + " " + Arrays.toString(waypoints)); } } @Override public void stopWaypoints() { // Stop the thread that is doing the "navigation" by terminating its // navigation process, clear all the waypoints, and stop the vehicle. synchronized (_navigationLock) { if (_navigationTask != null) { _navigationTask.cancel(); _navigationTask = null; _waypoints = new UtmPose[0]; setVelocity(new Twist(DEFAULT_TWIST)); } } sendWaypointUpdate(WaypointState.CANCELLED); } @Override public UtmPose[] getWaypoints() { UtmPose[] wpts = new UtmPose[_waypoints.length]; synchronized (_navigationLock) { System.arraycopy(_waypoints, 0, wpts, 0, wpts.length); } return wpts; } @Override public WaypointState getWaypointStatus() { synchronized (_navigationLock) { if (_waypoints.length > 0) { return _isAutonomous.get() ? WaypointState.PAUSED : WaypointState.GOING; } else { return WaypointState.DONE; } } } /** * Returns the current estimated 6D velocity of the vehicle. */ public Twist getVelocity() { return _velocities.clone(); } /** * Sets a desired 6D velocity for the vehicle. */ public void setVelocity(Twist vel) { _velocities = vel.clone(); } @Override public boolean isAutonomous() { return _isAutonomous.get(); } @Override public void setAutonomous(boolean isAutonomous) { _isAutonomous.set(isAutonomous); // Set velocities to zero to allow for safer transitions _velocities = new Twist(DEFAULT_TWIST); } /** * Performs cleanup functions in preparation for stopping the server. */ public void shutdown() { stopWaypoints(); stopCamera(); _isAutonomous.set(false); _isConnected.set(false); _updateTimer.cancel(); _updateTimer.purge(); _navigationTimer.cancel(); _navigationTimer.purge(); _captureTimer.cancel(); _captureTimer.purge(); } }
package edu.jhu.thrax.tools; import java.io.BufferedWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.logging.Logger; import edu.jhu.jerboa.util.FileManager; import edu.jhu.thrax.ThraxConfig; import edu.jhu.thrax.util.io.LineReader; public class ParaphraseOverlap { private static final Logger logger = Logger.getLogger(ParaphraseOverlap.class.getName()); private static final String DELIM = String.format(" %s ", ThraxConfig.DELIMITER_REGEX); public static void main(String[] args) { String grammar_file = null; String reference_file = null; String weight_file = null; String output_file = null; for (int i = 0; i < args.length; i++) { if ("-g".equals(args[i]) && (i < args.length - 1)) { grammar_file = args[++i]; } else if ("-r".equals(args[i]) && (i < args.length - 1)) { reference_file = args[++i]; } else if ("-w".equals(args[i]) && (i < args.length - 1)) { weight_file = args[++i]; } else if ("-o".equals(args[i]) && (i < args.length - 1)) { output_file = args[++i]; } } if (grammar_file == null) { logger.severe("No grammar specified."); return; } if (reference_file == null) { logger.severe("No reference file specified."); return; } if (weight_file == null) { logger.severe("No weight file specified."); return; } if (output_file == null) { logger.severe("No output file specified."); return; } HashMap<String, Double> rule_to_score = new HashMap<String, Double>(); HashMap<String, Double> weights = new HashMap<String, Double>(); try { LineReader reference_reader = new LineReader(reference_file); while (reference_reader.hasNext()) { String line = reference_reader.next().trim(); rule_to_score.put(line, null); } reference_reader.close(); int num_references = rule_to_score.keySet().size(); LineReader weights_reader = new LineReader(weight_file); while (weights_reader.hasNext()) { String line = weights_reader.next().trim(); if (line.isEmpty()) continue; String[] fields = line.split("\\s+"); weights.put(fields[0], Double.parseDouble(fields[1])); } weights_reader.close(); ArrayList<Double> missed = new ArrayList<Double>(); LineReader reader = new LineReader(grammar_file); System.err.print("["); int rule_count = 0; while (reader.hasNext()) { String rule_line = reader.next().trim(); String[] fields = rule_line.split(DELIM); String rule = fields[0] + " ||| " + fields[1] + " ||| " + fields[2]; double score = 0; String[] features = fields[3].split("\\s+"); for (String f : features) { String[] parts = f.split("="); if (weights.containsKey(parts[0])) score += weights.get(parts[0]) * Double.parseDouble(parts[1]); } if (rule_to_score.containsKey(rule)) { if (++rule_count % 10000 == 0) System.err.print("-"); if (rule_to_score.get(rule) == null) rule_to_score.put(rule, score); else rule_to_score.put(rule, Math.max(score, rule_to_score.get(rule))); } else { missed.add(score); } } System.err.println("]"); reader.close(); double[] matched = new double[rule_count]; int i = 0; for (Double s : rule_to_score.values()) if (s != null) matched[i] = s; rule_to_score = null; i = 0; double[] unmatched = new double[missed.size()]; for (double s : missed) unmatched[i++] = s; missed = null; int num_correct = matched.length; int num_paraphrases = matched.length + unmatched.length; System.err.println("References: " + num_references); System.err.println("Matched: " + num_correct); System.err.println("Unmatched: " + (num_references - num_correct)); System.err.println("Nonmatching: " + unmatched.length); Arrays.sort(matched); Arrays.sort(unmatched); int m = 0, u = 0; BufferedWriter score_writer = FileManager.getWriter(output_file); while (m < matched.length && u < unmatched.length) { if (matched[m] < unmatched[u]) { if (m % 200 == 0) score_writer.write(matched[m] + "\t" + (num_correct / (double) num_references) + "\t" + (num_correct / (double) num_paraphrases) + "\n"); m++; num_correct } else { u++; } num_paraphrases } score_writer.close(); } catch (IOException e) { logger.severe(e.getMessage()); } } }
package okapi; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; import guru.nidi.ramltester.RamlDefinition; import guru.nidi.ramltester.RamlLoaders; import guru.nidi.ramltester.restassured.RestAssuredClient; import io.vertx.core.Vertx; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.folio.okapi.MainCluster; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(VertxUnitRunner.class) public class MainClusterTest { private final Logger logger = LoggerFactory.getLogger("okapi"); private final int port = Integer.parseInt(System.getProperty("port", "9130")); Async async; Vertx vertx; RamlDefinition api; public MainClusterTest() { } @Before public void setUp(TestContext context) { async = context.async(); api = RamlLoaders.fromFile("src/main/raml").load("okapi.raml"); RestAssured.port = port; async.complete(); } @After public void tearDown(TestContext context) { async = context.async(); if (vertx == null) { async.complete(); } else { vertx.close(x -> { vertx = null; async.complete(); }); } } @Test public void testHelp(TestContext context) { async = context.async(); String[] args = {"help"}; MainCluster.main1(args, res -> { vertx = res.succeeded() ? res.result() : null; Assert.assertTrue(res.succeeded()); async.complete(); }); } @Test public void testBadOption(TestContext context) { async = context.async(); String[] args = {"-bad-option"}; MainCluster.main1(args, res -> { vertx = res.succeeded() ? res.result() : null; Assert.assertFalse(res.succeeded()); async.complete(); }); } @Test public void testBadMode(TestContext context) { async = context.async(); String[] args = {"bad", "-enable-metrics"}; MainCluster.main1(args, res -> { vertx = res.succeeded() ? res.result() : null; Assert.assertFalse(res.succeeded()); async.complete(); }); } @Test public void testNoArgs(TestContext context) { async = context.async(); String[] args = {}; MainCluster.main1(args, res -> { Assert.assertFalse(res.succeeded()); vertx = res.succeeded() ? res.result() : null; async.complete(); }); } @Test public void testDevMode(TestContext context) { async = context.async(); String[] args = {"dev"}; MainCluster.main1(args, res -> { vertx = res.succeeded() ? res.result() : null; Assert.assertTrue("main1 " + res.cause(), res.succeeded()); RestAssuredClient c; Response r; c = api.createRestAssured(); r = c.given().get("/_/version").then().statusCode(200).log().ifError().extract().response(); Assert.assertTrue("raml: " + c.getLastReport().toString(), c.getLastReport().isEmpty()); async.complete(); }); } @Test public void testDeploymentMode(TestContext context) { async = context.async(); String[] args = {"deployment"}; MainCluster.main1(args, res -> { vertx = res.succeeded() ? res.result() : null; Assert.assertTrue("main1" + res.cause(), res.succeeded()); RestAssuredClient c; Response r; c = api.createRestAssured(); r = c.given().get("/_/deployment/modules").then().statusCode(200).log().ifError().extract().response(); Assert.assertTrue("raml: " + c.getLastReport().toString(), c.getLastReport().isEmpty()); async.complete(); }); } @Test public void testProxyMode(TestContext context) { async = context.async(); String[] args = {"proxy"}; MainCluster.main1(args, res -> { vertx = res.succeeded() ? res.result() : null; Assert.assertTrue("main1 " + res.cause(), res.succeeded()); RestAssuredClient c; Response r; c = api.createRestAssured(); r = c.given().get("/_/proxy/modules").then().statusCode(200).log().ifError().extract().response(); Assert.assertTrue("raml: " + c.getLastReport().toString(), c.getLastReport().isEmpty()); async.complete(); }); } @Test public void testClusterMode(TestContext context) { async = context.async(); String[] args = {"cluster"}; MainCluster.main1(args, res -> { vertx = res.succeeded() ? res.result() : null; Assert.assertTrue("main1 " + res.cause(), res.succeeded()); RestAssuredClient c; Response r; c = api.createRestAssured(); r = c.given().get("/_/proxy/modules").then().statusCode(200).log().ifError().extract().response(); Assert.assertTrue("raml: " + c.getLastReport().toString(), c.getLastReport().isEmpty()); async.complete(); }); } @Test public void testClusterModeFail1(TestContext context) { async = context.async(); String[] args = {"cluster", "-cluster-host", "foobar", "-cluster-port", "5701"}; MainCluster.main1(args, res -> { vertx = res.succeeded() ? res.result() : null; Assert.assertTrue("main1 " + res.cause(), res.failed()); async.complete(); }); } @Test public void testClusterModeFail2(TestContext context) { async = context.async(); String[] args = {"cluster", "-hazelcast-config-file", "foobar"}; MainCluster.main1(args, res -> { vertx = res.succeeded() ? res.result() : null; Assert.assertTrue("main1 " + res.cause(), res.failed()); async.complete(); }); } @Test public void testClusterModeFail3(TestContext context) { async = context.async(); String[] args = {"cluster", "-hazelcast-config-cp", "foobar"}; MainCluster.main1(args, res -> { vertx = res.succeeded() ? res.result() : null; Assert.assertTrue("main1 " + res.cause(), res.failed()); async.complete(); }); } @Test public void testClusterModeFail4(TestContext context) { async = context.async(); String[] args = {"cluster", "-hazelcast-config-url", "foobar"}; MainCluster.main1(args, res -> { vertx = res.succeeded() ? res.result() : null; Assert.assertTrue("main1 " + res.cause(), res.failed()); async.complete(); }); } }
package org.spine3.protobuf; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.Any; import com.google.protobuf.AnyOrBuilder; import com.google.protobuf.Descriptors; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Message; import org.spine3.Internal; import org.spine3.annotations.AnnotationsProto; import org.spine3.base.Command; import org.spine3.type.StringTypeValue; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Throwables.propagate; import static org.spine3.validate.Validate.checkNotDefault; import static org.spine3.validate.Validate.checkNotEmptyOrBlank; /** * A wrapper for the Protobuf type URL. * * <p>Consists of the two parts separated with {@link TypeUrl#SEPARATOR}. * The first part is the type URL prefix (for example, "type.googleapis.com"); * the second one is the fully-qualified Protobuf type name. * * @see Any#getTypeUrl() * @see Descriptors.FileDescriptor#getFullName() * @author Alexander Yevsyukov */ public final class TypeUrl extends StringTypeValue { @VisibleForTesting /* package */ static final String SEPARATOR = "/"; private static final Pattern TYPE_URL_SEPARATOR_PATTERN = Pattern.compile(SEPARATOR); private static final String PROTOBUF_PACKAGE_SEPARATOR = "."; private static final Pattern PROTOBUF_PACKAGE_SEPARATOR_PATTERN = Pattern.compile('\\' + PROTOBUF_PACKAGE_SEPARATOR); public static final String GOOGLE_TYPE_URL_PREFIX = "type.googleapis.com"; private static final String GOOGLE_PROTOBUF_PACKAGE = "google.protobuf"; /** The prefix of the type URL. */ private final String prefix; /** The name of the Protobuf type. */ private final String typeName; private TypeUrl(String prefix, String typeName) { super(composeTypeUrl(prefix, typeName)); this.prefix = checkNotEmptyOrBlank(prefix, "typeUrlPrefix"); this.typeName = checkNotEmptyOrBlank(typeName, "typeName"); } private static String composeTypeUrl(String typeUrlPrefix, String typeName) { final String url = typeUrlPrefix + SEPARATOR + typeName; return url; } /** * Creates a new type URL taking it from the passed message instance. * * @param msg an instance to get the type URL from */ public static TypeUrl of(Message msg) { return of(msg.getDescriptorForType()); } /** * Creates a new instance by the passed descriptor taking its type URL. * * @param descriptor the descriptor of the type */ public static TypeUrl of(Descriptor descriptor) { final String typeUrlPrefix = getTypeUrlPrefix(descriptor); return new TypeUrl(typeUrlPrefix, descriptor.getFullName()); } /** * Creates a new instance from the passed type URL or type name. * * @param typeUrlOrName the type URL of the Protobuf message type or its fully-qualified name */ @Internal public static TypeUrl of(String typeUrlOrName) { // TODO:2016-07-08:alexander.litus: tests checkNotEmptyOrBlank(typeUrlOrName, "type URL or name"); final TypeUrl typeUrl = isTypeUrl(typeUrlOrName) ? ofTypeUrl(typeUrlOrName) : ofTypeName(typeUrlOrName); return typeUrl; } private static boolean isTypeUrl(String str) { return str.contains(SEPARATOR); } private static TypeUrl ofTypeUrl(String typeNameOrUrl) { final String[] parts = TYPE_URL_SEPARATOR_PATTERN.split(typeNameOrUrl); if (parts.length != 2 || parts[0].trim().isEmpty() || parts[1].trim().isEmpty()) { throw propagate( new InvalidProtocolBufferException("Invalid Protobuf type url encountered: " + typeNameOrUrl)); } return new TypeUrl(parts[0], parts[1]); } private static TypeUrl ofTypeName(String typeName) { final TypeUrl typeUrl = KnownTypes.getTypeUrl(typeName); return typeUrl; } /** * Obtains the type URL of the message enclosed into the instance of {@link Any}. * * @param any the instance of {@code Any} containing a {@code Message} instance of interest * @return a type URL */ public static TypeUrl ofEnclosed(AnyOrBuilder any) { final TypeUrl typeUrl = ofTypeUrl(any.getTypeUrl()); return typeUrl; } /** * Obtains the type URL of the command message. * * <p>The passed command must have non-default message. * * @param command the command from which to get the URL * @return the type URL of the command message */ public static TypeUrl ofCommand(Command command) { final Any any = command.getMessage(); checkNotDefault(any); final TypeUrl typeUrl = ofEnclosed(any); return typeUrl; } /** * Obtains the type URL for the passed message class. */ public static TypeUrl of(Class<? extends Message> clazz) { final Message defaultInstance = com.google.protobuf.Internal.getDefaultInstance(clazz); final TypeUrl result = of(defaultInstance); return result; } /** * * * @param message * @return */ // TODO:2016-07-08:alexander.litus: refactor public static String getTypeUrlPrefix(Descriptor message) { // TODO:2016-07-08:alexander.litus: tests final Descriptors.FileDescriptor file = message.getFile(); if (file.getPackage().equals(GOOGLE_PROTOBUF_PACKAGE)) { return GOOGLE_TYPE_URL_PREFIX; } final String result = file.getOptions() .getExtension(AnnotationsProto.typeUrlPrefix); return result; } /** {@inheritDoc} */ @Override public String value() { // Expose method to other packages. return super.value(); } public String getPrefix() { return prefix; } public String getTypeName() { return typeName; } /** Returns the unqualified name of the Protobuf type, for example: `StringValue`. */ public String getSimpleName() { if (typeName.contains(PROTOBUF_PACKAGE_SEPARATOR)) { final String[] parts = PROTOBUF_PACKAGE_SEPARATOR_PATTERN.split(typeName); checkState(parts.length > 0, "Invalid type name: " + typeName); final String result = parts[parts.length - 1]; return result; } else { return typeName; } } }
package com.gravity.map; import java.util.List; import java.util.Map; import org.newdawn.slick.Graphics; import org.newdawn.slick.SlickException; import org.newdawn.slick.geom.Vector2f; import org.newdawn.slick.tiled.GroupObject; import org.newdawn.slick.tiled.Layer; import org.newdawn.slick.tiled.ObjectGroup; import org.newdawn.slick.tiled.Tile; import org.newdawn.slick.tiled.TiledMapPlus; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.gravity.entity.TriggeredText; import com.gravity.entity.TriggeredTextEntity; import com.gravity.geom.Rect; import com.gravity.physics.Collidable; import com.gravity.root.GameplayControl; public class TileWorld implements GameWorld { public final int height; public final int width; public final int tileHeight; public final int tileWidth; private List<Collidable> entityNoCalls, entityCallColls; private List<TriggeredText> triggeredTexts; private Map<Layer, List<MovingCollidable>> movingCollMap; private final String name; public final TiledMapPlus map; private final GameplayControl controller; private interface CollidableCreator { Collidable createCollidable(Rect r); } public TileWorld(String name, TiledMapPlus map, GameplayControl controller) { this.map = map; this.controller = controller; this.name = name; // Get width/height this.tileWidth = map.getTileWidth(); this.tileHeight = map.getTileHeight(); this.width = map.getWidth() * tileWidth; this.height = map.getHeight() * tileHeight; } /** * Process a layer of the map for collisions. Merge adjacent tiles vertically, then horizontally. * * @param layerName * the name of the layer in the map to process. * @param creator * a Creator to create collidables for * @return a list of collidables in this layer. Returns an empty list if the list does not exist. */ private List<Collidable> processLayer(String layerName, CollidableCreator creator) { boolean[][] visited = new boolean[map.getWidth()][map.getHeight()]; List<Collidable> res = Lists.newArrayList(); int layer = 0; try { layer = map.getLayerID(layerName); } catch (NullPointerException e) { System.err.println("WARNING: Layer " + layerName + " not found, returning empty collidables list."); return res; } int first, i, j, tileId; for (i = 0; i < map.getWidth(); i++) { first = 0; while (first < map.getHeight()) { tileId = map.getTileId(i, first, layer); visited[i][first] = true; if (tileId != 0) { j = first + 1; while (j < map.getHeight() && map.getTileId(i, j, layer) != 0) { visited[i][j] = true; j++; } Rect r = new Rect(i * tileWidth, first * tileHeight, tileWidth, tileHeight * (j - first)); res.add(creator.createCollidable(r)); first = j; } else { first++; } } } for (j = 0; j < map.getHeight(); j++) { first = 0; while (first < map.getWidth()) { tileId = visited[first][j] ? 0 : map.getTileId(first, j, layer); if (tileId != 0) { i = first + 1; while (i < map.getWidth() && map.getTileId(i, j, layer) != 0) { visited[i][j] = true; i++; } Rect r = new Rect(first * tileWidth, j * tileHeight, tileWidth * (i - first), tileHeight); res.add(creator.createCollidable(r)); first = i; } else { first++; } } } return res; } @Override public void initialize() { // Iterate over and find all tiles Layer terrain = map.getLayer("map"); if (terrain != null) { } else { entityNoCalls = processLayer(TILES_LAYER_NAME, new CollidableCreator() { @Override public Collidable createCollidable(Rect r) { return new StaticCollidable(r); } }); entityCallColls = processLayer(SPIKES_LAYER_NAME, new CollidableCreator() { @Override public Collidable createCollidable(Rect r) { return new SpikeEntity(controller, r); } }); entityNoCalls.addAll(processLayer(BOUNCYS_LAYER_NAME, new CollidableCreator() { @Override public Collidable createCollidable(Rect r) { return new BouncyTile(r); } })); } triggeredTexts = Lists.newArrayList(); for (Layer layer : map.getLayers()) { int x = Integer.parseInt(layer.props.getProperty("x", "-1")); int y = Integer.parseInt(layer.props.getProperty("y", "-1")); String text = layer.props.getProperty("text", null); if (x < 0 || y < 0 || text == null) { continue; } // if text layer is found, make layer invisible layer.visible = false; TriggeredText triggeredText; triggeredText = new TriggeredText(x, y, text); System.out.println("found text layer: " + text); triggeredTexts.add(triggeredText); try { for (Tile tile : layer.getTiles()) { Rect r = new Rect(tile.x * tileWidth, tile.y * tileHeight, tileWidth, tileHeight); TriggeredTextEntity tte = new TriggeredTextEntity(r, triggeredText); entityCallColls.add(tte); } } catch (SlickException e) { throw new RuntimeException("Unable to get tiles for map layer " + layer.name, e); } } movingCollMap = Maps.newHashMap(); for (Layer layer : map.getLayers()) { final float speed = Float.parseFloat(layer.props.getProperty("speed", "-1.0")); final int transX = Integer.parseInt(layer.props.getProperty("translationX", "-22222")); final int transY = Integer.parseInt(layer.props.getProperty("translationY", "-22222")); if (speed < 0 || transX == -22222 || transY == -22222) continue; // Found a moving layer. layer.visible = false; List<Collidable> colls = processLayer(layer.name, new CollidableCreator() { @Override public Collidable createCollidable(Rect r) { return new MovingCollidable(controller, tileWidth, tileHeight, r, transX, transY, speed); } }); entityNoCalls.addAll(colls); List<MovingCollidable> movingColls = Lists.newArrayList(); for (Collidable c : colls) { movingColls.add((MovingCollidable)c); } movingCollMap.put(layer, movingColls); } } @Override public int getHeight() { return height; } @Override public int getWidth() { return width; } @Override public List<Collidable> getTerrainEntitiesNoCalls() { return entityNoCalls; } @Override public Layer getLayer(String name) { return map.getLayer(name); } @Override public void render(Graphics g, int offsetX, int offsetY) { //@formatter:off /* * // if we need to draw hitboxes again: g.pushTransform(); g.translate(offsetX, offsetY); g.setColor(Color.red); for (Collidable e : entityNoCalls) { g.draw(e.getRect(0).toShape()); } g.setColor(Color.white); g.resetTransform(); g.popTransform(); */ //@formatter:on map.render(offsetX, offsetY); } @Override public List<Collidable> getTerrainEntitiesCallColls() { return entityCallColls; } @Override public List<Vector2f> getPlayerStartPositions() { Layer layer = map.getLayer(PLAYERS_LAYER_NAME); if (layer == null) { System.err.println("WARNING: Map \"" + name + "\" doesn't contain player start positions, using default positions instead."); return Lists.newArrayList(PLAYER_ONE_DEFAULT_STARTPOS, PLAYER_TWO_DEFAULT_STARTPOS); } layer.visible = false; try { List<Vector2f> res = Lists.newArrayList(); for (Tile tile : layer.getTiles()) { res.add(new Vector2f(tile.x * tileWidth, tile.y * tileHeight)); } Preconditions.checkArgument(res.size() == 2, "Wrong number of player start positions in map \"" + name + "\", expected 2 but found " + res.size()); return res; } catch (SlickException e) { System.err.println(e); return Lists.newArrayList(PLAYER_ONE_DEFAULT_STARTPOS, PLAYER_TWO_DEFAULT_STARTPOS); } } @Override public Rect getFinishRect() { GroupObject object; try { ObjectGroup group = map.getObjectGroup(MARKERS_LAYER_NAME); object = group.getObject(FINISH_MARKER_NAME); return new Rect(object.x, object.y, object.width, object.height); } catch (NullPointerException e) { System.err.println("No marker layer found for map " + map + " using right edge of map instead"); return new Rect((map.getWidth() - 1) * tileWidth, 0, tileWidth, getHeight()); } } @Override public String toString() { return "TileWorld [height=" + height + ", width=" + width + ", name=" + name + ", map=" + map + "]"; } public List<TriggeredText> getTriggeredTexts() { return triggeredTexts; } public Map<Layer, List<MovingCollidable>> getMovingCollMap() { return movingCollMap; } }
package common.template.engine; import common.controllers.PageData; import play.twirl.api.Html; import java.util.List; import java.util.Locale; /** * Service that provides HTML pages, using some sort of template engine. */ public interface TemplateEngine { /** * Injects the page data into the template with the given name. * @param templateName name of the template * @param pageData data to be injected in the template * @param locales locales used for i18n * @return string of the HTML generated with the template and the given page data * @throws TemplateNotFoundException when the given template name does not correspond to an existing template * @throws TemplateRenderException when the provided page data could not be injected to the template */ String render(final String templateName, final PageData pageData, final List<Locale> locales); /** * Injects the page data into the template with the given name. * @param templateName name of the template * @param pageData data to be injected in the template * @param locales locales used for i18n * @return HTML generated with the template and the given page data * @throws TemplateNotFoundException when the given template name does not correspond to an existing template * @throws TemplateRenderException when the provided page data could not be injected to the template */ default Html renderToHtml(final String templateName, final PageData pageData, final List<Locale> locales) { return new Html(render(templateName, pageData, locales)); } }
package au.com.codeka.common.model; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import java.util.TreeMap; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Duration; import org.joda.time.Interval; import org.joda.time.Seconds; /** * This class is used to simulate a \c Star. It need to have the same logic as ctrl/simulation.py * on the server, and we go to great pains to keep them in sync. */ public class Simulation { private LogHandler mLogHandler; private DateTime mNow; private static int sNumSimulations; private static DateTime year2k = new DateTime(2000, 1, 1, 0, 0); public Simulation() { mNow = DateTime.now(DateTimeZone.UTC); } public Simulation(LogHandler log) { mNow = DateTime.now(DateTimeZone.UTC); mLogHandler = log; } public static int getNumRunningSimulations() { return sNumSimulations; } protected void log(String message) { if (mLogHandler != null) { mLogHandler.log(message); } } /** * Simulate the given star, and make sure it's "current". * @param star */ public void simulate(BaseStar star) { sNumSimulations ++; log(String.format("Begin simulation for '%s'", star.getName())); HashSet<String> empireKeys = new HashSet<String>(); for (BaseColony colony : star.getColonies()) { if (!empireKeys.contains(colony.getEmpireKey())) { empireKeys.add(colony.getEmpireKey()); } } // if there's any missing EmpirePresence objects, add them now // figure out the start time, which is the oldest last_simulation time DateTime startTime = getSimulateStartTime(star); if (startTime == null) { // Nothing worth simulating... return; } DateTime endTime = mNow; // if we have less than a few seconds of time to simulate, we'll extend the end time // a little to ensure there's no rounding errors and such if (endTime.minusSeconds(3).compareTo(startTime) < 0) { endTime = startTime.plusSeconds(3); } // We'll simulate in "prediction mode" for an extra bit of time so that we can get a // more accurate estimate of the end time for builds. We won't *record* the population // growth and such, just the end time of builds. We'll also record the time that the // population drops below a certain threshold so that we can warn the player. DateTime predictionTime = endTime.plusHours(24); BaseStar predictionStar = null; while (true) { Duration dt = Duration.standardMinutes(15); DateTime stepEndTime = startTime.plus(dt); if (stepEndTime.compareTo(endTime) < 0) { simulateStepForAllEmpires(dt, startTime, star, empireKeys); startTime = stepEndTime; } else if (stepEndTime.compareTo(predictionTime) < 0) { if (predictionStar == null) { log(" log("Prediction phase beginning..."); log(" mNow = endTime; dt = new Interval(startTime, endTime).toDuration(); if (dt.getMillis() > 1000) { // last little bit of the simulation simulateStepForAllEmpires(dt, startTime, star, empireKeys); } startTime = startTime.plus(dt); predictionStar = star.clone(); dt = Duration.standardMinutes(15); } simulateStepForAllEmpires(dt, startTime, predictionStar, empireKeys); startTime = stepEndTime; } else { break; } } if (predictionStar != null) { // copy the end times for builds from prediction_star_pb for (BaseBuildRequest starBuildRequest : star.getBuildRequests()) { for (BaseBuildRequest predictedBuildRequest : predictionStar.getBuildRequests()) { if (starBuildRequest.getKey().equals(predictedBuildRequest.getKey())) { starBuildRequest.setEndTime(predictedBuildRequest.getEndTime()); } } } // any fleets that *will be* destroyed, remember the time of their death for (BaseFleet fleet : star.getFleets()) { for (BaseFleet predictedFleet : predictionStar.getFleets()) { if (fleet.getKey().equals(predictedFleet.getKey())) { log(String.format("Fleet #%s updating timeDestroyed to: %s", fleet.getKey(), predictedFleet.getTimeDestroyed())); fleet.setTimeDestroyed(predictedFleet.getTimeDestroyed()); } } } // if the empire is going to run out of resources, save that time as well. for (BaseEmpirePresence empirePresence : star.getEmpirePresences()) { for (BaseEmpirePresence predictedEmpirePresence : predictionStar.getEmpirePresences()) { if (empirePresence.getKey().equals(predictedEmpirePresence.getKey())) { empirePresence.setGoodsZeroTime(predictedEmpirePresence.getGoodsZeroTime()); } } } // also, the prediction combat report (if any) is the one to use star.setCombatReport(predictionStar.getCombatReport()); star.setLastSimulation(endTime); } sNumSimulations } private DateTime getSimulateStartTime(BaseStar star) { DateTime lastSimulation = star.getLastSimulation(); if (lastSimulation == null) { for (BaseFleet fleet : star.getFleets()) { if (lastSimulation == null || fleet.getStateStartTime().compareTo(lastSimulation) < 0) { lastSimulation = fleet.getStateStartTime(); } } } return lastSimulation; } private void simulateStepForAllEmpires(Duration dt, DateTime now, BaseStar star, Set<String> empireKeys) { log(String.format("- Step [dt=%.2f hrs] [now=%s]", (float)(dt.toStandardSeconds().getSeconds()) / 3600.0f, now)); for (String empireKey : empireKeys) { log(String.format("-- Empire [%s]", empireKey == null ? "Native" : empireKey)); simulateStep(dt, now, star, empireKey); } // Don't forget to simulate combat for this step as well (TODO: what to do if combat continues // after the prediction phase?) simulateCombat(star, now, dt); } private static boolean equalEmpireKey(String keyOne, String keyTwo) { if (keyOne == null && keyTwo == null) { return true; } if (keyOne == null || keyTwo == null) { return false; } return keyOne.equals(keyTwo); } private void simulateStep(Duration dt, DateTime now, BaseStar star, String empireKey) { float totalGoods = 50.0f; float totalMinerals = 50.0f; float totalPopulation = 0.0f; float maxGoods = 50.0f; float maxMinerals = 50.0f; BaseEmpirePresence empire = null; for (BaseEmpirePresence e : star.getEmpires()) { if (!equalEmpireKey(e.getEmpireKey(), empireKey)) { continue; } empire = e; totalGoods = empire.getTotalGoods(); totalMinerals = empire.getTotalMinerals(); maxGoods = empire.getMaxGoods(); maxMinerals = empire.getMaxMinerals(); } float dtInHours = ((float) dt.getMillis()) / (1000.0f * 3600.0f); float goodsDeltaPerHour = 0.0f; float mineralsDeltaPerHour = 0.0f; for (BaseColony colony : star.getColonies()) { if (!equalEmpireKey(colony.getEmpireKey(), empireKey)) { continue; } log(String.format("--- Colony [planetIndex=%d] [population=%.2f]", colony.getPlanetIndex(), colony.getPopulation())); BasePlanet planet = star.getPlanets()[colony.getPlanetIndex() - 1]; // calculate the output from farming this turn and add it to the star global float goods = colony.getPopulation() * colony.getFarmingFocus() * (planet.getFarmingCongeniality() / 100.0f); colony.setGoodsDelta(goods); totalGoods += goods * dtInHours; goodsDeltaPerHour += goods; log(String.format(" Goods: [delta=%.2f / hr] [this turn=%.2f]", goods, goods * dtInHours)); // calculate the output from mining this turn and add it to the star global float minerals = colony.getPopulation() * colony.getMiningFocus() * (planet.getMiningCongeniality() / 100.0f); colony.setMineralsDelta(minerals); totalMinerals += minerals * dtInHours; mineralsDeltaPerHour += minerals; log(String.format(" Minerals: [delta=%.2f / hr] [this turn=%.2f]", goods, goods * dtInHours)); totalPopulation += colony.getPopulation(); // work out the amount of taxes this colony has generated in the last turn float taxPerPopulationPerHour = 0.012f; float taxThisTurn = taxPerPopulationPerHour * dtInHours * colony.getPopulation(); log(String.format(" Taxes %.2f + %.2f = %.2f uncollected", colony.getUncollectedTaxes(), taxThisTurn, colony.getUncollectedTaxes() + taxThisTurn)); colony.setUncollectedTaxes(colony.getUncollectedTaxes() + taxThisTurn); } // A second loop though the colonies, once the goods/minerals have been calculated. This way, // goods minerals are shared between colonies for (BaseColony colony : star.getColonies()) { if (!equalEmpireKey(colony.getEmpireKey(), empireKey)) { continue; } ArrayList<BaseBuildRequest> buildRequests = new ArrayList<BaseBuildRequest>(); for (BaseBuildRequest br : star.getBuildRequests()) { if (br.getColonyKey().equals(colony.getKey())) { buildRequests.add(br); } } // not all build requests will be processed this turn. We divide up the population // based on the number of ACTUAL build requests they'll be working on this turn int numValidBuildRequests = 0; for (BaseBuildRequest br : buildRequests) { if (br.getStartTime().compareTo(now.plus(dt)) > 0) { continue; } // the end_time will be accurate, since it'll have been updated last step if (br.getEndTime().compareTo(now) < 0 && br.getEndTime().compareTo(year2k) > 0) { continue; } // as long as it's started but hasn't finished, we'll be working on it this turn numValidBuildRequests += 1; } // If we have pending build requests, we'll have to update them as well if (numValidBuildRequests > 0) { float totalWorkers = colony.getPopulation() * colony.getConstructionFocus(); float workersPerBuildRequest = totalWorkers / numValidBuildRequests; log(String.format("--- Building [buildRequests=%d] [planetIndex=%d] [totalWorker=%.2f]", numValidBuildRequests, colony.getPlanetIndex(), totalWorkers)); // OK, we can spare at least ONE population if (workersPerBuildRequest < 1.0f) { workersPerBuildRequest = 1.0f; } // divide the minerals up per build request, so they each get a share. I'm not sure // if we should portion minerals out by how 'big' the build request is, but we'll // see how this goes initially float mineralsPerBuildRequest = totalMinerals / numValidBuildRequests; for (BaseBuildRequest br : buildRequests) { Design design = BaseDesignManager.i.getDesign(br.getDesignKind(), br.getDesignID()); log(String.format("---- Building [design=%s %s] [count=%d]", br.getDesignKind(), br.getDesignID(), br.getCount())); DateTime startTime = br.getStartTime(); if (startTime.compareTo(now.plus(dt)) > 0) { continue; } // So the build time the design specifies is the time to build the structure with // 100 workers available. Double the workers and you halve the build time. Halve // the workers and you double the build time. float totalBuildTimeInHours = br.getCount() * design.getBuildCost().getTimeInSeconds() / 3600.0f; totalBuildTimeInHours *= (100.0 / workersPerBuildRequest); // the number of hours of work required, assuming we have all the minerals we need float timeRemainingInHours = (1.0f - br.getProgress(false)) * totalBuildTimeInHours; if (timeRemainingInHours < (10.0f / 3600.0f)) { // if there's less than 10 seconds to go, just say it's done now. timeRemainingInHours = 0.0f; } log(String.format(" Time [total=%.2f hrs] [remaining=%.2f hrs]", totalBuildTimeInHours, timeRemainingInHours)); float dtUsed = dtInHours; if (startTime.isAfter(now)) { Duration startOffset = new Interval(now, startTime).toDuration(); dtUsed -= startOffset.getMillis() / (1000.0f * 3600.0f); } if (dtUsed > timeRemainingInHours) { dtUsed = timeRemainingInHours; } // what is the current amount of time we have now as a percentage of the total build // time? float progressThisTurn = dtUsed / totalBuildTimeInHours; if (progressThisTurn <= 0) { DateTime endTime; timeRemainingInHours = (1.0f - br.getProgress(false)) * totalBuildTimeInHours; if (timeRemainingInHours < (10.0f / 3600.0f)) { endTime = now; } else { endTime = now.plus((long)(timeRemainingInHours * 3600.0f * 1000.0f)); } if (br.getEndTime().compareTo(endTime) > 0) { br.setEndTime(endTime); } continue; } // work out how many minerals we require for this turn float mineralsRequired = br.getCount() * design.getBuildCost().getCostInMinerals() * progressThisTurn; if (mineralsRequired > mineralsPerBuildRequest) { // if we don't have enough minerals, we'll just do a percentage of the work // this turn totalMinerals -= mineralsPerBuildRequest; float percentMineralsAvailable = mineralsPerBuildRequest / mineralsRequired; br.setProgress(br.getProgress(false) + (progressThisTurn * percentMineralsAvailable)); log(String.format(" Progress %.4f%% + %.4f%% (this turn, adjusted - %.4f%% originally) ", br.getProgress(false) * 100.0f, progressThisTurn * percentMineralsAvailable * 100.0f, progressThisTurn * 100.0f)); } else { // awesome, we have enough minerals so we can make some progress. We'll start by // removing the minerals we need from the global pool... totalMinerals -= mineralsRequired; br.setProgress(br.getProgress(false) + progressThisTurn); log(String.format(" Progress %.4f%% + %.4f%% (this turn)", br.getProgress(false) * 100.0f, progressThisTurn * 100.0f)); } mineralsDeltaPerHour -= mineralsRequired / dtInHours; log(String.format(" Minerals [required=%.2f] [available=%.2f] [available per build=%.2f]", mineralsRequired, totalMinerals, mineralsPerBuildRequest)); // adjust the end_time for this turn timeRemainingInHours = (1.0f - br.getProgress(false)) * totalBuildTimeInHours; DateTime endTime = now.plus((long)(dtUsed * 1000 * 3600) + (long)(timeRemainingInHours * 1000 * 3600)); br.setEndTime(endTime); log(String.format(" End Time: %s (%.2f hrs)", endTime, Seconds.secondsBetween(now, endTime).getSeconds() / 3600.0f)); if (br.getProgress(false) >= 1.0f) { // if we've finished this turn, just set progress br.setProgress(1.0f); } } } } // Finally, update the population. The first thing we need to do is evenly distribute goods // between all of the colonies. float totalGoodsPerHour = totalPopulation / 10.0f; if (totalPopulation > 0.0001f && totalGoodsPerHour < 10.0f) { totalGoodsPerHour = 10.0f; } float totalGoodsRequired = totalGoodsPerHour * dtInHours; goodsDeltaPerHour -= totalGoodsPerHour; // If we have more than total_goods_required stored, then we're cool. Otherwise, our population // suffers... float goodsEfficiency = 1.0f; if (totalGoodsRequired > totalGoods && totalGoodsRequired > 0) { goodsEfficiency = totalGoods / totalGoodsRequired; } log(String.format("--- Updating Population [goods required=%.2f] [goods available=%.2f] [efficiency=%.2f]", totalGoodsRequired, totalGoods, goodsEfficiency)); // subtract all the goods we'll need totalGoods -= totalGoodsRequired; if (totalGoods <= 0.0f) { // We've run out of goods! That's bad... totalGoods = 0.0f; if (empire != null) { if (empire.getGoodsZeroTime() == null || empire.getGoodsZeroTime().isAfter(now.plus(dt))) { log(String.format(" GOODS HAVE HIT ZERO")); empire.setGoodsZeroTime(now.plus(dt)); } } } // now loop through the colonies and update the population/goods counter for (BaseColony colony : star.getColonies()) { if (!equalEmpireKey(colony.getEmpireKey(), empireKey)) { continue; } float populationIncrease; if (goodsEfficiency >= 1.0f) { populationIncrease = Math.max(colony.getPopulation(), 10.0f); populationIncrease *= colony.getPopulationFocus() * 0.5f; } else { populationIncrease = Math.max(colony.getPopulation(), 10.0f); populationIncrease *= (1.0f - colony.getPopulationFocus()); populationIncrease *= 0.25f * (goodsEfficiency - 1.0f); } colony.setPopulationDelta(populationIncrease); float populationIncreaseThisTurn = populationIncrease * dtInHours; float newPopulation = colony.getPopulation() + populationIncreaseThisTurn; if (newPopulation < 1.0f) { newPopulation = 0.0f; } else if (newPopulation > colony.getMaxPopulation()) { newPopulation = colony.getMaxPopulation(); } if (newPopulation < 100.0f && colony.isInCooldown()) { newPopulation = 100.0f; } log(String.format(" Colony[%d]: [delta=%.2f] [new=%.2f]", colony.getPlanetIndex(), populationIncrease, newPopulation)); colony.setPopulation(newPopulation); } if (totalGoods > maxGoods) { totalGoods = maxGoods; } if (totalMinerals > maxMinerals) { totalMinerals = maxMinerals; } if (empire != null) { empire.setTotalGoods(totalGoods); empire.setTotalMinerals(totalMinerals); empire.setDeltaGoodsPerHour(goodsDeltaPerHour); empire.setDeltaMineralsPerHour(mineralsDeltaPerHour); } } private void simulateCombat(BaseStar star, DateTime now, Duration dt) { // if there's no fleets in ATTACKING mode, then there's nothing to do int numAttacking = 0; for (BaseFleet fleet : star.getFleets()) { if (fleet.getState() != BaseFleet.State.ATTACKING || isDestroyed(fleet, now)) { continue; } numAttacking ++; } if (numAttacking == 0) { return; } // get the existing combat report, or create a new one BaseCombatReport combatReport = star.getCombatReport(); if (combatReport == null) { log(String.format("-- Combat [new combat report] [%d attacking]", numAttacking)); combatReport = star.createCombatReport(null); star.setCombatReport(combatReport); } else { // remove any rounds that are in the future for (int i = 0; i < combatReport.getCombatRounds().size(); i++) { BaseCombatReport.CombatRound round = combatReport.getCombatRounds().get(i); if (round.getRoundTime().isAfter(now)) { combatReport.getCombatRounds().remove(i); i } } log(String.format("-- Combat, [loaded %d rounds] [%d attacking]", combatReport.getCombatRounds().size(), numAttacking)); } DateTime attackStartTime = null; for (BaseFleet fleet : star.getFleets()) { if (fleet.getState() != BaseFleet.State.ATTACKING) { continue; } if (attackStartTime == null || attackStartTime.isAfter(fleet.getStateStartTime())) { attackStartTime = fleet.getStateStartTime(); } } if (attackStartTime.isBefore(now)) { attackStartTime = now; } // round up to the next minute attackStartTime = new DateTime( attackStartTime.getYear(), attackStartTime.getMonthOfYear(), attackStartTime.getDayOfMonth(), attackStartTime.getHourOfDay(), attackStartTime.getMinuteOfHour(), 0); attackStartTime = attackStartTime.plusMinutes(1); // if they're not supposed to start attacking yet, then don't start if (attackStartTime.isAfter(now.plus(dt))) { return; } // attacks happen in turns, each turn lasts for one minute DateTime attackEndTime = now.plus(dt); while (now.isBefore(attackEndTime)) { if (now.isBefore(attackStartTime)) { now = now.plusMinutes(1); if (now.isAfter(attackStartTime)) { now = attackStartTime; } continue; } BaseCombatReport.CombatRound round = new BaseCombatReport.CombatRound(); round.setStarKey(star.getKey()); round.setRoundTime(now); log(String.format("--- Round #%d [%s]", combatReport.getCombatRounds().size() + 1, now)); boolean stillAttacking = simulateCombatRound(now, star, round); if (combatReport.getStartTime() == null) { combatReport.setStartTime(now); } combatReport.setEndTime(now); combatReport.getCombatRounds().add(round); if (!stillAttacking) { log(String.format("--- Combat finished.")); break; } now = now.plusMinutes(1); } } private boolean simulateCombatRound(DateTime now, BaseStar star, BaseCombatReport.CombatRound round) { for (BaseFleet fleet : star.getFleets()) { if (isDestroyed(fleet, now)) { continue; } BaseCombatReport.FleetSummary fleetSummary = new BaseCombatReport.FleetSummary(fleet); round.getFleets().add(fleetSummary); } // now we go through the fleet summaries and join them together for (int i = 0; i < round.getFleets().size(); i++) { BaseCombatReport.FleetSummary fs1 = round.getFleets().get(i); for (int j = i + 1; j < round.getFleets().size(); j++) { BaseCombatReport.FleetSummary fs2 = round.getFleets().get(j); if (!isSameEmpire(fs1.getEmpireKey(), fs2.getEmpireKey())) { continue; } if (!fs1.getDesignID().equals(fs2.getDesignID())) { continue; } if (fs1.getFleetStance() != fs2.getFleetStance()) { continue; } if (fs1.getFleetState() != fs2.getFleetState()) { continue; } // same empire, same design, same stance/state -- join 'em! fs1.addShips(fs2); round.getFleets().remove(j); j } } for (int i = 0; i < round.getFleets().size(); i++) { BaseCombatReport.FleetSummary fleet = round.getFleets().get(i); fleet.setIndex(i); } // each fleet targets and fires at once TreeMap<Integer, Double> hits = new TreeMap<Integer, Double>(); for (BaseCombatReport.FleetSummary fleet : round.getFleets()) { if (fleet.getFleetState() != BaseFleet.State.ATTACKING) { continue; } BaseCombatReport.FleetSummary target = findTarget(round, fleet); if (target == null) { // if there's no more available targets, then we're no longer attacking log(String.format(" Fleet #%d no suitable target.", fleet.getIndex())); continue; } else { log(String.format(" Fleet #%d attacking fleet #%d", fleet.getIndex(), target.getIndex())); } ShipDesign fleetDesign = (ShipDesign) BaseDesignManager.i.getDesign(DesignKind.SHIP, fleet.getDesignID()); float damage = fleet.getNumShips() * fleetDesign.getBaseAttack(); log(String.format(" Fleet #%d (%s x %.2f) hit by fleet #%d (%s x %.2f) for %.2f damage", target.getIndex(), target.getDesignID(), target.getNumShips(), fleet.getIndex(), fleet.getDesignID(), fleet.getNumShips(), damage)); Double totalDamage = hits.get(target.getIndex()); if (totalDamage == null) { hits.put(target.getIndex(), new Double(damage)); } else { hits.put(target.getIndex(), new Double(totalDamage + damage)); } BaseCombatReport.FleetAttackRecord attackRecord = new BaseCombatReport.FleetAttackRecord( round.getFleets(), fleet.getIndex(), target.getIndex(), damage); round.getFleetAttackRecords().add(attackRecord); } // any fleets that were attacked this round will want to change to attacking for the next // round, if they're not attacking already... for (BaseCombatReport.FleetSummary fleet : round.getFleets()) { if (!hits.keySet().contains(fleet.getIndex())) { continue; } for (BaseFleet targetFleet : fleet.getFleets()) { if (targetFleet.getState() == BaseFleet.State.IDLE) { ShipDesign targetDesign = (ShipDesign) BaseDesignManager.i.getDesign(DesignKind.SHIP, fleet.getDesignID()); ArrayList<ShipEffect> effects = targetDesign.getEffects(ShipEffect.class); for (ShipEffect effect : effects) { effect.onAttacked(star, targetFleet); } } } } // next, apply the damage from this round for (BaseCombatReport.FleetSummary fleet : round.getFleets()) { Double damage = hits.get(fleet.getIndex()); if (damage == null) { continue; } ShipDesign fleetDesign = (ShipDesign) BaseDesignManager.i.getDesign(DesignKind.SHIP, fleet.getDesignID()); damage /= fleetDesign.getBaseDefence(); fleet.removeShips((float) (double) damage); log(String.format(" Fleet #%d %.2f ships lost (%.2f ships remaining)", fleet.getIndex(), damage, fleet.getNumShips())); BaseCombatReport.FleetDamagedRecord damageRecord = new BaseCombatReport.FleetDamagedRecord( round.getFleets(), fleet.getIndex(), (float) damage.doubleValue()); round.getFleetDamagedRecords().add(damageRecord); // go through the "real" fleets and apply the damage as well for (String fleetKey : fleet.getFleetKeys()) { BaseFleet realFleet = star.findFleet(fleetKey); float newNumShips = (float)(realFleet.getNumShips() - damage); if (newNumShips <= 0) { newNumShips = 0; } realFleet.setNumShips(newNumShips); if (realFleet.getNumShips() <= 0.0f) { realFleet.setTimeDestroyed(now); } if (damage <= 0) { break; } } } // if all the fleets are friendly (or running away), we can stop attacking boolean enemyExists = false; for (int i = 0; i < star.getFleets().size(); i++) { BaseFleet fleet1 = star.getFleets().get(i); if (isDestroyed(fleet1, now) || fleet1.getState() == BaseFleet.State.MOVING) { continue; } for (int j = i + 1; j < star.getFleets().size(); j++) { BaseFleet fleet2 = star.getFleets().get(j); if (isDestroyed(fleet2, now)) { continue; } if (!isSameEmpire(fleet1.getEmpireKey(), fleet2.getEmpireKey())) { if (fleet2.getState() == BaseFleet.State.MOVING) { // if it's moving, it doesn't count continue; } enemyExists = true; } } } if (!enemyExists) { for (BaseFleet fleet : star.getFleets()) { // switch back from attacking mode to idle if (fleet.getState() == BaseFleet.State.ATTACKING) { fleet.idle(now); } } return false; } return true; } /** * Searches for an enemy fleet with the lowest priority. */ private BaseCombatReport.FleetSummary findTarget(BaseCombatReport.CombatRound round, BaseCombatReport.FleetSummary fleet) { int foundPriority = 9999; BaseCombatReport.FleetSummary foundFleet = null; for (BaseCombatReport.FleetSummary otherFleet : round.getFleets()) { if (isSameEmpire(fleet.getEmpireKey(), otherFleet.getEmpireKey())) { continue; } if (otherFleet.getFleetState() == BaseFleet.State.MOVING) { continue; } ShipDesign design = (ShipDesign) BaseDesignManager.i.getDesign(DesignKind.SHIP, otherFleet.getDesignID()); if (foundFleet == null || design.getCombatPriority() < foundPriority) { foundFleet = otherFleet; foundPriority = design.getCombatPriority(); } } return foundFleet; } private static boolean isSameEmpire(String key1, String key2) { if (key1 == null && key2 == null) { return true; } if (key1 == null || key2 == null) { return false; } return key1.equals(key2); } private boolean isDestroyed(BaseFleet fleet, DateTime now) { if (fleet.getTimeDestroyed() != null && !fleet.getTimeDestroyed().isAfter(now)) { return true; } return false; } /** * This interface is used to help debug the simulation code. Implement it to receive a bunch * of debug log messages during the simulation process. */ public interface LogHandler { void log(String message); } }
package loci.common; public final class Constants { public static final String ENCODING = ome.scifio.common.Constants.ENCODING; public static final double EPSILON = ome.scifio.common.Constants.EPSILON; }
// Checker.java package loci.plugins; import ij.IJ; import java.util.HashSet; import java.util.Iterator; public final class Checker { // -- Constants -- /** Identifier for checking the Bio-Formats library is present. */ public static final int BIO_FORMATS = 1; /** Identifier for checking the OME Java OME-XML library is present. */ public static final int OME_JAVA_XML = 2; /** Identifier for checking the OME Java OMEDS library is present. */ public static final int OME_JAVA_DS = 3; /** Identifier for checking the JGoodies Forms library is present. */ public static final int FORMS = 4; // -- Constructor -- private Checker() { } // -- Utility methods -- /** Checks whether the given class is available. */ public static boolean checkClass(String className) { try { Class.forName(className); } catch (Throwable t) { return false; } return true; } /** * Checks for a required library. * @param library One of:<ul> * <li>BIO_FORMATS</li> * <li>OME_JAVA_XML</li> * <li>OME_JAVA_DS</li> * <li>FORMS</li> * </ul> */ public static void checkLibrary(int library, HashSet missing) { switch (library) { case BIO_FORMATS: checkLibrary("loci.formats.FormatHandler", "bio-formats.jar", missing); checkLibrary("org.apache.poi.poifs.filesystem.POIFSFileSystem", "poi-loci.jar", missing); break; case OME_JAVA_XML: checkLibrary("ome.xml.OMEXMLNode", "ome-xml.jar", missing); break; case OME_JAVA_DS: checkLibrary("org.openmicroscopy.ds.DataServer", "ome-java.jar", missing); checkLibrary("org.apache.xmlrpc.XmlRpcClient", "xmlrpc-1.2-b1.jar", missing); checkLibrary("org.apache.commons.httpclient.HttpClient", "commons-httpclient-2.0-rc2.jar", missing); checkLibrary("org.apache.commons.logging.Log", "commons-logging.jar", missing); break; case FORMS: checkLibrary("com.jgoodies.forms.layout.FormLayout", "forms-1.0.4.jar", missing); break; } } /** * Checks whether the given class is available; if not, * adds the specified JAR file name to the hash set * (presumably to report it missing to the user). */ public static void checkLibrary(String className, String jarFile, HashSet missing) { if (!checkClass(className)) missing.add(jarFile); } /** Checks for a new enough version of the Java Runtime Environment. */ public static boolean checkJava() { String version = System.getProperty("java.version"); double ver = Double.parseDouble(version.substring(0, 3)); if (ver < 1.4) { IJ.error("LOCI Plugins", "Sorry, the LOCI plugins require Java 1.4 or later." + "\nYou can download ImageJ with JRE 5.0 from the ImageJ web site."); return false; } return true; } /** Checks whether the version of ImageJ is new enough. */ public static boolean checkImageJ() { boolean success; try { String version = IJ.getVersion(); success = version != null && version.compareTo("1.34") >= 0; } catch (NoSuchMethodError err) { success = false; } if (!success) { IJ.error("LOCI Plugins", "Sorry, the LOCI plugins require ImageJ v1.34 or later."); } return success; } /** * Reports missing libraries in the given hash set to the user. * @return true iff no libraries are missing (the hash set is empty). */ public static boolean checkMissing(HashSet missing) { int num = missing.size(); if (num == 0) return true; StringBuffer sb = new StringBuffer(); sb.append("The following librar"); sb.append(num == 1 ? "y was" : "ies were"); sb.append(" not found:"); Iterator iter = missing.iterator(); for (int i=0; i<num; i++) sb.append("\n " + iter.next()); String them = num == 1 ? "it" : "them"; sb.append("\nPlease download "); sb.append(them); sb.append(" from the LOCI website at"); sb.append("\n http: sb.append("\nand place "); sb.append(them); sb.append(" in the ImageJ plugins folder."); IJ.error("LOCI Plugins", sb.toString()); return false; } }
// Updater.java package loci.plugins; import ij.IJ; import ij.gui.GenericDialog; import ij.plugin.PlugIn; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import loci.common.RandomAccessInputStream; import loci.formats.FormatTools; import loci.plugins.util.WindowTools; public class Updater implements PlugIn { // -- Constants -- public static final String TRUNK_BUILD = "http://hudson.openmicroscopy.org.uk/job/LOCI/lastSuccessfulBuild/" + "artifact/trunk/artifacts/loci_tools.jar"; public static final String TODAYS_BUILD = "http://loci.wisc.edu/software/daily/loci_tools.jar"; public static final String YESTERDAYS_BUILD = "http://loci.wisc.edu/software/daily.old/loci_tools.jar"; public static final String STABLE_BUILD = "http://loci.wisc.edu/software/loci_tools.jar"; public static final String STABLE_VERSION = "4.0.1"; public static final String REGISTRY = "http://upgrade.openmicroscopy.org.uk"; public static final String[] REGISTRY_PROPERTIES = new String[] { "version", "os.name", "os.version", "os.arch", "java.runtime.version", "java.vm.vendor" }; public static final int CHUNK_SIZE = 8192; // -- Fields -- /** Flag indicating whether last operation was canceled. */ public boolean canceled; /** Path to loci_tools.jar. */ private String urlPath; // -- PlugIn API methods -- public void run(String arg) { GenericDialog upgradeDialog = new GenericDialog("Update LOCI Plugins"); String[] options = new String[] {"Trunk build", "Daily build (today)", "Daily build (yesterday)", "Stable build (" + STABLE_VERSION + ")"}; upgradeDialog.addChoice("Release", options, options[0]); upgradeDialog.showDialog(); if (upgradeDialog.wasCanceled()) { canceled = true; return; } String release = upgradeDialog.getNextChoice(); if (release.equals(options[0])) urlPath = TRUNK_BUILD; else if (release.equals(options[1])) urlPath = TODAYS_BUILD; else if (release.equals(options[2])) urlPath = YESTERDAYS_BUILD; else urlPath = STABLE_BUILD; install(urlPath); } // -- Utility methods -- /** Check if a new stable version is available. */ public static boolean newVersionAvailable() { // connect to the registry StringBuffer query = new StringBuffer(REGISTRY); for (int i=0; i<REGISTRY_PROPERTIES.length; i++) { if (i == 0) query.append("?"); else query.append(";"); query.append(REGISTRY_PROPERTIES[i]); query.append("="); if (i == 0) query.append(FormatTools.VERSION); else { try { query.append(URLEncoder.encode( System.getProperty(REGISTRY_PROPERTIES[i]), "UTF-8")); } catch (UnsupportedEncodingException e) { } } } try { URLConnection conn = new URL(query.toString()).openConnection(); conn.setUseCaches(false); conn.addRequestProperty("User-Agent", "OMERO.imagej"); conn.connect(); // retrieve latest version number from the registry InputStream in = conn.getInputStream(); StringBuffer latestVersion = new StringBuffer(); while (true) { int data = in.read(); if (data == -1) break; latestVersion.append((char) data); } in.close(); // check to see if version reported by registry is greater than // the current version - version number should be in "x.x.x" format String[] version = latestVersion.toString().split("\\."); String[] thisVersion = FormatTools.VERSION.split("\\."); for (int i=0; i<thisVersion.length; i++) { int subVersion = Integer.parseInt(thisVersion[i]); try { int registrySubVersion = Integer.parseInt(version[i]); if (registrySubVersion > subVersion) return true; if (registrySubVersion < subVersion) return false; } catch (NumberFormatException e) { return false; } } } catch (IOException e) { } return false; } /** Download and install a JAR file from the given URL. */ public static void install(final String urlPath) { String pluginsDirectory = IJ.getDirectory("plugins"); String jarPath = pluginsDirectory + File.separator + "loci_tools.jar"; String downloadPath = jarPath + ".tmp"; // if an old version exists, remove it File plugin = new File(downloadPath); if (plugin.exists()) plugin.delete(); // download new version to plugins directory IJ.showStatus("Connecting to download server..."); try { URL url = new URL(urlPath); URLConnection urlConn = url.openConnection(); int total = urlConn.getContentLength(); byte[] buf = new byte[total]; DataInputStream in = new DataInputStream( new BufferedInputStream(urlConn.getInputStream())); int off = 0; while (off < total) { IJ.showStatus("Downloading loci_tools.jar..."); IJ.showProgress((double) off / total); int len = CHUNK_SIZE; if (off + len > total) len = total - off; int r = in.read(buf, off, len); if (r <= 0) { IJ.showStatus(""); IJ.showMessage("Error downloading the LOCI plugins."); return; } off += r; } in.close(); IJ.showProgress(1); IJ.showStatus("Saving loci_tools.jar..."); FileOutputStream out = new FileOutputStream(plugin); out.write(buf); out.close(); boolean success = plugin.renameTo(new File(jarPath)); if (!success) { IJ.showStatus(""); IJ.showMessage("The LOCI plugins have been downloaded to:\n" + downloadPath + "\n" + "The JAR file could not be renamed to loci_tools.jar.\n" + "Please rename " + downloadPath + " to\n" + jarPath + "\n" + "and restart ImageJ to complete the upgrade process."); return; } } catch (IOException e) { IJ.showStatus(""); IJ.showProgress(1); WindowTools.reportException(e, false, "An error occurred while downloading the LOCI plugins"); return; } IJ.showStatus(""); IJ.showMessage("The LOCI plugins have been downloaded.\n" + "Please restart ImageJ to complete the upgrade process."); } }
package gov.nara.nwts.ftapp.gui; import gov.nara.nwts.ftapp.FTDriver; import gov.nara.nwts.ftapp.gui.MergePanel.FilterOptions.FilterOptionTest; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ContainerEvent; import java.awt.event.ContainerListener; import java.util.TreeMap; import java.util.Vector; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.RowFilter; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; /** * User interface allowing the results of 2 or more FileAnalyzer actions (File Test or File Import) to be compared * The merge options that are presented are dynamically adjusted based on the number of {@link gov.nara.nwts.ftapp.gui.SummaryPanel Summary Result Panels} that are being displayed. At least 2 summary panels must be present in order for the merge options to appear. * @author TBrady * */ class MergePanel extends MyBorderPanel { public static final String STR_IGNORE = "*Ignore*"; public static final String STR_YES = "\"Yes\""; private static final long serialVersionUID = 1L; JPanel tp; DefaultTableModel tm; JTable jt; Vector<JComboBox<String>> mergeOptions; JComboBox<FilterOptionTest> filterOptions; Box box; JButton b; TableRowSorter<TableModel> sorter; DirectoryTable parent; MergePanel(DirectoryTable dt) { parent = dt; mergeOptions = new Vector<JComboBox<String>>(); String[] cols = {"Key","Run 1", "Run 2"}; tm = new DefaultTableModel(cols,5); jt = new MergeTable(tm); jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); jt.setPreferredScrollableViewportSize(new Dimension(600,200)); sorter = new TableRowSorter<TableModel>(tm); jt.setRowSorter(sorter); filterOptions = new JComboBox<FilterOptionTest>(); tp = addBorderPanel("Merged Counts"); tp.add(new JScrollPane(jt), BorderLayout.CENTER); JPanel p = addPanel("", BorderLayout.SOUTH); JButton save = new JButton("Export Table"); save.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent arg0) { new TableSaver(parent,tm,jt,"Stats"); } } ); p.add(save); p = addPanel("Specify Merge Options", BorderLayout.NORTH); p.setLayout(new BorderLayout()); JPanel pp = new JPanel(new BorderLayout()); JPanel p1 = new JPanel(new FlowLayout(FlowLayout.CENTER)); JPanel p2 = new JPanel(new FlowLayout(FlowLayout.CENTER)); p.add(pp, BorderLayout.SOUTH); p.setPreferredSize(new Dimension(600,200)); pp.add(p1, BorderLayout.NORTH); pp.add(p2, BorderLayout.SOUTH); filterOptions.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { filter(); } }); p2.add(filterOptions); b = new JButton("Merge Summaries"); b.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { TreeMap<String,Object[]> merge = new TreeMap<String,Object[]>(); int compcount = 1; int col = 0; for(int i=DirectoryTable.TAB_MERGE + 1; i < parent.tabs.getTabCount(); i++){ JComboBox<String> opt = MergePanel.this.mergeOptions.get(i-DirectoryTable.TAB_MERGE-1); if (opt.getSelectedItem().equals(STR_IGNORE)) continue; compcount++; } String[] colnames = new String[compcount]; colnames[0] = "Key"; for(int i=DirectoryTable.TAB_MERGE + 1; i < parent.tabs.getTabCount(); i++){ JComboBox<String> opt = MergePanel.this.mergeOptions.get(i-DirectoryTable.TAB_MERGE-1); if (opt.getSelectedItem().equals(STR_IGNORE)) continue; col++; colnames[col] = parent.tabs.getTitleAt(i); DefaultTableModel tm = ((SummaryPanel)parent.tabs.getComponentAt(i)).st.tm; for(int r=0; r<tm.getRowCount(); r++){ String key = (String)tm.getValueAt(r, 0); Object[] v = merge.get(key); if (v == null) { v = new Object[compcount]; v[0] = key; for(int x=1;x<v.length; x++){ v[x]=""; } merge.put(key, v); } if (opt.getSelectedItem().equals(STR_YES)) { v[col] = STR_YES; } else { Object obj = tm.getValueAt(r, opt.getSelectedIndex()-1); v[col] = (obj == null) ? "" : obj.toString(); } } } tm.setColumnIdentifiers(colnames); tm.setRowCount(0); filterOptions.removeAllItems(); for(FilterOptions fo: FilterOptions.values()) { fo.addOptions(filterOptions, tm); } DefaultTableCellRenderer tcr = new DefaultTableCellRenderer(); tcr.setBackground(Color.PINK); Vector<Vector<Object>> vec = new Vector<Vector<Object>>(); for(Object[]ar: merge.values()) { Vector<Object>v=new Vector<Object>(); for(Object a: ar) { v.add(a); } vec.add(v); tallyCounts(filterOptions, v); } Vector<String>vcol = new Vector<String>(); for(String coln: colnames) { vcol.add(coln); } tm.setDataVector(vec, vcol); jt.repaint(); }}); p1.add(b); parent.tabs.addContainerListener(new ContainerListener(){ public void componentAdded(ContainerEvent arg0) { refreshOptions(); } public void componentRemoved(ContainerEvent arg0) { refreshOptions(); }}); p1 = new JPanel(); p.add(new JScrollPane(p1), BorderLayout.CENTER); box = new Box(BoxLayout.Y_AXIS); p1.add(box); } void tallyCounts(JComboBox<FilterOptionTest> cb, Vector<Object> v) { for(int i=0; i<cb.getItemCount(); i++) { FilterOptionTest fot = cb.getItemAt(i); if (fot.eOpt == FilterOptions.All_Items) { fot.count++; } else if (fot.eOpt == FilterOptions.ColEmpty) { if ("".equals(v.get(fot.col))) { fot.count++; } } else if (fot.eOpt == FilterOptions.ColHasValue) { if (!"".equals(v.get(fot.col))) { fot.count++; } } else { boolean match = true; for(int j=2; j<v.size(); j++) { if (!v.get(1).equals(v.get(j))) { match = false; break; } } if (fot.eOpt == FilterOptions.Matches && match) { fot.count++; } else if (fot.eOpt == FilterOptions.Mismatches && !match){ fot.count++; } } } } void filter() { RowFilter<TableModel,Integer> rf = new RowFilter<TableModel,Integer>(){ public boolean include(Entry<? extends TableModel, ? extends Integer> row) { FilterOptionTest fo = (FilterOptionTest)filterOptions.getSelectedItem(); if (fo == null) { return true; } else if (fo.eOpt == FilterOptions.All_Items) { return true; } else if (fo.col == -1) { boolean matches = true; Object comp = row.getValue(1); for(int i=2; i<row.getValueCount(); i++){ if (comp == null) { if (row.getValue(i) != null) { matches = false; break; } } else if (!comp.equals(row.getValue(i))) { matches = false; break; } } if (fo.eOpt == FilterOptions.Matches) { return matches; } else { return !matches; } } else { Object comp = row.getValue(fo.col); if (comp==null) { return fo.eOpt == FilterOptions.ColEmpty; } if (comp.equals("")) { return fo.eOpt == FilterOptions.ColEmpty; } return fo.eOpt == FilterOptions.ColHasValue; } } }; sorter.setRowFilter(rf); } void refreshOptions() { mergeOptions.clear(); box.removeAll(); for(int i=DirectoryTable.TAB_MERGE + 1; i < parent.tabs.getTabCount(); i++){ JPanel p = new JPanel(); box.add(p); p.add(new JLabel(parent.tabs.getTitleAt(i))); SummaryPanel sp = (SummaryPanel)parent.tabs.getComponentAt(i); Vector<String> v = new Vector<String>(); v.add(STR_IGNORE); for(int c=0;c<sp.st.details.size(); c++){ v.add(sp.st.details.get(c).header); } v.add(STR_YES); JComboBox<String> cb = new JComboBox<String>(v); cb.setSelectedIndex((v.size() > 2) ? 2 : (v.size() == 2) ? 1 : 0); mergeOptions.add(cb); p.add(cb); parent.frame.pack(); parent.frame.repaint(); } } class MergeTable extends JTable { private static final long serialVersionUID = 1L; DefaultTableCellRenderer def; DefaultTableCellRenderer diff; MergeTable(DefaultTableModel tm) { super(tm); def = new DefaultTableCellRenderer(); diff = new DefaultTableCellRenderer(); diff.setBackground(Color.PINK); } public TableCellRenderer getCellRenderer(int row, int col){ if (col <= 1) return def; Object o1 = this.getValueAt(row, col); Object o2 = this.getValueAt(row, col-1); if ((o1 == null) || (o2 == null)) return def; return (o1.equals(o2)) ? def : diff; } } /** * Options for filtering the results on the merge panel * @author TBrady * */ public enum FilterOptions { All_Items("Show All Items" , true), Matches("Show Matches", true), Mismatches("Show Mismatches",true), ColHasValue("Value Present",false), ColEmpty("Value Missing",false); boolean global; String name; FilterOptions(String name,boolean global) { this.name = name; this.global = global; } public void addOptions(JComboBox<FilterOptionTest> cb, TableModel tm) { if (global) { cb.addItem(new FilterOptionTest(this, -1, tm)); }else { for(int i=1; i<tm.getColumnCount(); i++) { FilterOptionTest test = new FilterOptionTest(this, i, tm); cb.addItem(test); } } } public class FilterOptionTest { FilterOptions eOpt; int col; int count = 0; String colname; public FilterOptionTest(FilterOptions eOpt, int col, TableModel tm) { this.eOpt = eOpt; this.col = col; this.colname = tm.getColumnName(col); } public String toString() { if (eOpt.global) { return eOpt.name + " - " + FTDriver.nf.format(this.count); } else { return eOpt.name +": " + colname+ " - " + FTDriver.nf.format(this.count); } } } }; }
package com.xqbase.tuna; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ClosedSelectorException; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.regex.Pattern; import com.xqbase.tuna.util.ByteArrayQueue; import com.xqbase.util.Log; import com.xqbase.util.Time; abstract class Attachment { SelectionKey selectionKey; abstract void closeChannel(); void finishClose() { selectionKey.cancel(); closeChannel(); } } /** * The encapsulation of a {@link SocketChannel} and its {@link SelectionKey}, * which corresponds to a TCP Socket. */ class Client extends Attachment { private static final int STATUS_CLOSED = 0; private static final int STATUS_IDLE = 1; private static final int STATUS_BUSY = 2; private static final int STATUS_DISCONNECTING = 3; int bufferSize = Connection.MAX_BUFFER_SIZE; int status = STATUS_IDLE; boolean resolving = false; ByteArrayQueue queue = new ByteArrayQueue(); Connection connection; SocketChannel socketChannel; Client(Connection connection) { this.connection = connection; connection.setHandler(new ConnectionHandler() { @Override public void send(byte[] b, int off, int len) { write(b, off, len); } @Override public void setBufferSize(int bufferSize) { boolean blocked = Client.this.bufferSize == 0; boolean toBlock = bufferSize <= 0; Client.this.bufferSize = Math.max(0, Math.min(bufferSize, Connection.MAX_BUFFER_SIZE)); if ((blocked ^ toBlock) && !resolving && status != STATUS_CLOSED) { // may be called before resolve interestOps(); } } @Override public void disconnect() { if (status == STATUS_IDLE) { // must be resolved finishClose(); } else if (status == STATUS_BUSY) { status = STATUS_DISCONNECTING; } } }); } void add(Selector selector, int ops) { try { selectionKey = socketChannel.register(selector, ops, this); } catch (IOException e) { throw new RuntimeException(e); } } /** * registers a {@link Client} and connects to a remote address * * @see ConnectorImpl#connect(Connection, String, int) * @throws IOException may throw "Network is unreachable" or "Protocol family unavailable", * and then socketChannel will be closed, and selectionKey will not be created */ void connect(Selector selector, InetSocketAddress socketAddress) throws IOException { resolving = false; try { socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); } catch (IOException e) { throw new RuntimeException(e); } try { socketChannel.connect(socketAddress); add(selector, SelectionKey.OP_CONNECT); } catch (IOException e) { // May throw "Network is unreachable" or "Protocol family unavailable", // and then socketChannel will be closed, and selectionKey will not be created closeChannel(); throw e; } } void interestOps() { selectionKey.interestOps((bufferSize == 0 ? 0 : SelectionKey.OP_READ) | (status == STATUS_IDLE ? 0 : SelectionKey.OP_WRITE)); } void write() throws IOException { int len = queue.length(); int fromLen = len; while (len > 0) { int bytesWritten = socketChannel.write(ByteBuffer.wrap(queue.array(), queue.offset(), len)); if (bytesWritten == 0) { unblock(len, fromLen); return; } len = queue.remove(bytesWritten).length(); } unblock(len, fromLen); if (status == STATUS_DISCONNECTING) { finishClose(); } else { status = STATUS_IDLE; interestOps(); } } void write(byte[] b, int off, int len) { if (status != STATUS_IDLE) { int fromLen = queue.length(); block(queue.add(b, off, len).length(), fromLen); return; } int bytesWritten; try { bytesWritten = socketChannel.write(ByteBuffer.wrap(b, off, len)); } catch (IOException e) { startClose(); return; } if (len > bytesWritten) { int fromLen = queue.length(); block(queue.add(b, off + bytesWritten, len - bytesWritten).length(), fromLen); status = STATUS_BUSY; interestOps(); } } void startConnect() { status = STATUS_BUSY; } void finishConnect() { InetSocketAddress local = ((InetSocketAddress) socketChannel. socket().getLocalSocketAddress()); InetSocketAddress remote = ((InetSocketAddress) socketChannel. socket().getRemoteSocketAddress()); connection.onConnect(new ConnectionSession(local, remote)); } void startClose() { if (status != STATUS_CLOSED) { finishClose(); // Call "close()" before "onDisconnect()" // to avoid recursive "disconnect()". connection.onDisconnect(); } } @Override void closeChannel() { try { socketChannel.close(); } catch (IOException e) {} status = STATUS_CLOSED; } boolean isBusy() { return status >= STATUS_IDLE; } private boolean blocking = false; private void block(int len, int fromLen) { if (fromLen > 0) { blocking = true; connection.onQueue(len); } } private void unblock(int len, int fromLen) { if (len == fromLen) { return; } boolean fromBlocking = blocking; if (len == 0) { blocking = false; } if (fromBlocking) { connection.onQueue(len); } } } /** * The encapsulation of a {@link ServerSocketChannel} and its {@link SelectionKey}, * which corresponds to a TCP Server Socket */ class Server extends Attachment { ServerConnection serverConnection; ServerSocketChannel serverSocketChannel; /** * Opens a listening port and binds to a given address. * @param addr - The IP address to bind and the port to listen. * @throws IOException If an I/O error occurs when opening the port. */ Server(ServerConnection serverConnection, InetSocketAddress addr) throws IOException { this.serverConnection = serverConnection; bind(addr); } void bind(InetSocketAddress addr) throws IOException { try { serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); } catch (IOException e) { throw new RuntimeException(e); } try { serverSocketChannel.socket().bind(addr); } catch (IOException e) { closeChannel(); throw e; } } @Override void closeChannel() { try { serverSocketChannel.close(); } catch (IOException e) {} } } class Timer implements Comparable<Timer> { long uptime; long id; @Override public int compareTo(Timer o) { int result = Long.compare(uptime, o.uptime); return result == 0 ? Long.compare(id, o.id) : result; } @Override public String toString() { return new Date(uptime) + "/" + id; } } class Registrable { private SelectableChannel channel; private int interestOps; private Attachment att; /** @throws IOException if ServerSocket fails to Bind again */ Registrable(SelectionKey key) throws IOException { channel = key.channel(); interestOps = key.interestOps(); att = (Attachment) key.attachment(); key.cancel(); // Need to cancel ? if (!(att instanceof Server)) { return; } // Rebuild ServerSocketChannel Server server = (Server) att; InetSocketAddress addr = (InetSocketAddress) server.serverSocketChannel. socket().getLocalSocketAddress(); server.closeChannel(); server.bind(addr); channel = server.serverSocketChannel; } void register(Selector selector) throws IOException { att.selectionKey = channel.register(selector, interestOps, att); } } /** * The encapsulation of {@link Selector}, * which makes {@link Client} and {@link Server} working.<p> */ public class ConnectorImpl implements Connector, TimerHandler, EventQueue, Executor, AutoCloseable { private static Pattern hostName = Pattern.compile("[a-zA-Z]"); private static long nextId = 0; private volatile Selector selector; private boolean interrupted = false; private byte[] buffer = new byte[Connection.MAX_BUFFER_SIZE]; private TreeMap<Timer, Runnable> timerMap = new TreeMap<>(); private ConcurrentLinkedQueue<Runnable> eventQueue = new ConcurrentLinkedQueue<>(); private ExecutorService executor = Executors.newCachedThreadPool(); { try { selector = Selector.open(); } catch (IOException e) { throw new RuntimeException(e); } } /** @throws IOException if no IP address for the <code>host</code> could be found */ @Override public void connect(Connection connection, InetSocketAddress socketAddress) throws IOException { Client client = new Client(connection); client.startConnect(); if (!socketAddress.isUnresolved()) { client.connect(selector, socketAddress); return; } String host = socketAddress.getHostName(); int port = socketAddress.getPort(); if (host.indexOf(':') >= 0 || !hostName.matcher(host).find()) { // Connect immediately for IPv6 or IPv4 Address client.connect(selector, new InetSocketAddress(InetAddress.getByName(host), port)); return; } client.resolving = true; execute(() -> { try { // Resolve in Executor then Connect later InetAddress addr = InetAddress.getByName(host); invokeLater(() -> { try { client.connect(selector, new InetSocketAddress(addr, port)); } catch (IOException e) { // Call "onDisconnect()" when Connecting Failure connection.onDisconnect(); } }); } catch (IOException e) { // Call "onDisconnect()" when Resolving Failure invokeLater(connection::onDisconnect); } }); } @Override public Connector.Closeable add(ServerConnection serverConnection, InetSocketAddress socketAddress) throws IOException { Server server = new Server(serverConnection, socketAddress); try { server.selectionKey = server.serverSocketChannel. register(selector, SelectionKey.OP_ACCEPT, server); } catch (IOException e) { throw new RuntimeException(e); } return () -> { if (server.selectionKey.isValid()) { server.finishClose(); } }; } /** Consume events until interrupted */ public void doEvents() { while (!isInterrupted()) { Iterator<Map.Entry<Timer, Runnable>> it = timerMap.entrySet().iterator(); if (it.hasNext()) { long timeout = it.next().getKey().uptime - System.currentTimeMillis(); doEvents(timeout > 0 ? timeout : 0); } else { doEvents(-1); } } } private void invokeQueue() { long now = System.currentTimeMillis(); ArrayList<Runnable> runnables = new ArrayList<>(); Iterator<Map.Entry<Timer, Runnable>> it = timerMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Timer, Runnable> entry = it.next(); if (entry.getKey().uptime > now) { break; } runnables.add(entry.getValue()); it.remove(); } // call run() after iteration since run() may change timerMap for (Runnable runnable : runnables) { runnable.run(); } Runnable runnable; while ((runnable = eventQueue.poll()) != null) { runnable.run(); } } private static boolean shortTime(long millis) { return millis >= 0 && millis < 16; } private int epollCount = 0; private void checkEpoll(long timeout, long t, int keySize) { if (keySize > 0 || shortTime(timeout) || !shortTime(System.currentTimeMillis() - t) || !eventQueue.isEmpty() || Thread.currentThread().isInterrupted()) { epollCount = 0; return; } Set<SelectionKey> keys = selector.keys(); // TODO Remove: "select()" may exit immediately due to a Broken Connection ? for (SelectionKey key : keys) { Object att = key.attachment(); if (!(att instanceof Client)) { continue; } Client client = (Client) att; if (!client.socketChannel.isConnected() && !client.socketChannel.isConnectionPending()) { Log.w("Abort Registering New Selector, timeout = " + timeout + ", t0 = " + Time.toString(t, true) + ", t1 = " + Time.toString(System.currentTimeMillis(), true)); client.startClose(); epollCount = 0; return; } } // E-Poll Spin Detected epollCount ++; if (epollCount < 256) { return; } epollCount = 0; Log.w("Epoll Spin Detected, timeout = " + timeout + ", t0 = " + Time.toString(t, true) + ", t1 = " + Time.toString(System.currentTimeMillis(), true) + ", keys = " + keys.size()); Log.w("Begin Registering New Selector " + selector + " ..."); ArrayList<Registrable> regs = new ArrayList<>(); for (SelectionKey key : keys) { if (!key.isValid()) { Log.w("Invaid SelectionKey Detected"); continue; } try { regs.add(new Registrable(key)); } catch (IOException e) { // Ignored if ServerSocket fails to Bind again } } try { selector.close(); } catch (IOException e) {} try { selector = Selector.open(); for (Registrable reg : regs) { reg.register(selector); } } catch (IOException e) { throw new RuntimeException(e); } Log.w("End Registering New Selector " + selector); } /** * Consumes all events raised by registered Clients and Servers, * including network events (accept/connect/read/write) and user-defined events.<p> * * @param timeout Block for up to timeout milliseconds, or -1 to block indefinitely, * or 0 without blocking. * @return <b>true</b> if NETWORK events consumed;<br> * <b>false</b> if no NETWORK events raised, * whether or not user-defined events raised.<br> */ public boolean doEvents(long timeout) { long t = System.currentTimeMillis(); int keySize; try { keySize = timeout == 0 ? selector.selectNow() : timeout < 0 ? selector.select() : selector.select(timeout); } catch (IOException e) { throw new RuntimeException(e); } checkEpoll(timeout, t, keySize); if (keySize == 0) { invokeQueue(); return false; } Set<SelectionKey> selectedKeys = selector.selectedKeys(); for (SelectionKey key : selectedKeys) { if (!key.isValid()) { continue; } if (key.isAcceptable()) { Server server = (Server) key.attachment(); SocketChannel socketChannel; try { socketChannel = server.serverSocketChannel.accept(); if (socketChannel == null) { continue; } socketChannel.configureBlocking(false); } catch (IOException e) { throw new RuntimeException(e); } Client client = new Client(server.serverConnection.get()); client.socketChannel = socketChannel; client.add(selector, SelectionKey.OP_READ); client.finishConnect(); continue; } Client client = (Client) key.attachment(); try { if (key.isReadable()) { int bytesRead = client.socketChannel. read(ByteBuffer.wrap(buffer, 0, client.bufferSize)); if (bytesRead > 0) { client.connection.onRecv(buffer, 0, bytesRead); // may be closed by "onRecv" if (!key.isValid()) { continue; } } else if (bytesRead < 0) { client.startClose(); // Disconnected, so skip onQueue and onConnect continue; } } if (key.isWritable()) { client.write(); } else if (key.isConnectable() && client.socketChannel.finishConnect()) { client.finishConnect(); // "onConnect()" might call "disconnect()" if (client.isBusy()) { client.write(); } } } catch (IOException e) { client.startClose(); } } selectedKeys.clear(); invokeQueue(); return true; } @Override public TimerHandler.Closeable postAtTime(Runnable runnable, long uptime) { Timer timer = new Timer(); timer.uptime = uptime; timer.id = nextId; nextId ++; timerMap.put(timer, runnable); return () -> timerMap.remove(timer); } @Override public void invokeLater(Runnable runnable) { eventQueue.offer(runnable); try { selector.wakeup(); } catch (ClosedSelectorException e) {} } @Override public void execute(Runnable runnable) { executor.execute(runnable); } /** * Interrupts {@link #doEvents()} or {@link #doEvents(long)}.<p> * <b>Can be called outside main thread.</b> */ public void interrupt() { invokeLater(() -> interrupted = true); } /** * Tests whether the connector is interrupted, * and then the "interrupted" status is cleared. */ public boolean isInterrupted() { boolean interrupted_ = interrupted; interrupted = false; return interrupted_; } /** * Unregisters, closes all <b>Client</b>s and <b>Server</b>s, * then closes the Connector itself. */ @Override public void close() { executor.shutdown(); for (SelectionKey key : selector.keys()) { ((Attachment) key.attachment()).finishClose(); } try { selector.close(); } catch (IOException e) {} } }